Update to chromium 9659b08ea5a34f889dc4166217f438095ddc10d2

This commit is contained in:
Adam Barth
2015-07-16 22:10:38 -07:00
parent f99a1c19a6
commit a95585765e
208 changed files with 10443 additions and 1501 deletions

View File

@@ -0,0 +1,32 @@
commit 2f12ff08cc9215273040893a9b6c2b3fabccfb6b
Author: Adam Barth <abarth@chromium.org>
Date: Thu Jul 16 18:00:01 2015 -0700
Cherry-pick build fix from Mojo
diff --git a/services/android/rules.gni b/services/android/rules.gni
index 350b421..c2c286b 100644
--- a/services/android/rules.gni
+++ b/services/android/rules.gni
@@ -44,6 +44,10 @@ template("mojo_android_java_application") {
action(android_with_manifest_name) {
script = "${servicess_android_path}/add_manifest_entry.py"
+ deps = [
+ ":$android_standalone_name"
+ ]
+
input = dex_output_path
inputs = [
input,
@@ -74,6 +78,10 @@ template("mojo_android_java_application") {
action(target_name) {
script = rebase_path("mojo/public/tools/prepend.py", ".", mojo_root)
+ deps = [
+ ":$android_with_manifest_name"
+ ]
+
input = dex_with_manifest_output_path
inputs = [
input,

View File

@@ -86,16 +86,15 @@
'../android_webview/android_webview.gyp:android_webview_apk',
'../android_webview/android_webview.gyp:system_webview_apk',
'../android_webview/android_webview_shell.gyp:android_webview_shell_apk',
'../android_webview/android_webview_telemetry_shell.gyp:android_webview_telemetry_shell_apk',
'../chrome/android/chrome_apk.gyp:chrome_public_apk',
'../chrome/chrome.gyp:chrome_shell_apk',
'../chrome/chrome.gyp:chrome_sync_shell_apk',
'../remoting/remoting.gyp:remoting_apk',
],
}],
['target_arch == "arm" or target_arch == "arm64"', {
# TODO: Enable packed relocations for x64. See: b/20532404
['target_arch != "x64"', {
'dependencies': [
# The relocation packer is currently used only for ARM or ARM64.
'../third_party/android_platform/relocation_packer.gyp:android_relocation_packer_unittests#host',
],
}],
@@ -161,6 +160,7 @@
'dependencies': [
'../device/bluetooth/bluetooth.gyp:*',
'../device/device_tests.gyp:*',
'../gpu/skia_runner/skia_runner.gyp:*',
],
}],
['use_openssl==0 and (OS=="mac" or OS=="ios" or OS=="win")', {
@@ -379,6 +379,7 @@
'dependencies': [
'../chrome/chrome.gyp:crash_service',
'../chrome/chrome.gyp:installer_util_unittests',
'../chrome/chrome.gyp:setup_unittests',
# ../chrome/test/mini_installer requires mini_installer.
'../chrome/installer/mini_installer.gyp:mini_installer',
'../chrome_elf/chrome_elf.gyp:chrome_elf_unittests',
@@ -809,7 +810,6 @@
'../breakpad/breakpad.gyp:symupload#host',
'../breakpad/breakpad.gyp:minidump_dump#host',
'../breakpad/breakpad.gyp:minidump_stackwalk#host',
'../build/android/tests/multiple_proguards/multiple_proguards.gyp:multiple_proguards_test_apk',
'../build/android/pylib/device/commands/commands.gyp:chromium_commands',
'../cc/blink/cc_blink_tests.gyp:cc_blink_unittests',
'../cc/cc_tests.gyp:cc_perftests_apk',
@@ -887,6 +887,7 @@
'../chrome/chrome.gyp:chrome_shell_uiautomator_tests',
'../chrome/chrome.gyp:chromedriver_webview_shell_apk',
'../chrome/chrome.gyp:unit_tests_apk',
'../third_party/custom_tabs_client/src/custom_tabs_client.gyp:custom_tabs_client_example_apk',
],
}],
],
@@ -1070,6 +1071,7 @@
'../chrome/chrome.gyp:installer_util_unittests',
'../chrome/chrome.gyp:interactive_ui_tests',
'../chrome/chrome.gyp:performance_browser_tests',
'../chrome/chrome.gyp:setup_unittests',
'../chrome/chrome.gyp:sync_integration_tests',
'../chrome/chrome.gyp:unit_tests',
'../cloud_print/cloud_print.gyp:cloud_print_unittests',
@@ -1162,6 +1164,7 @@
'../chrome/chrome.gyp:chrome_app_unittests',
'../chrome/chrome.gyp:chromedriver_unittests',
'../chrome/chrome.gyp:installer_util_unittests',
'../chrome/chrome.gyp:setup_unittests',
'../chrome/chrome.gyp:unit_tests',
'../chrome_elf/chrome_elf.gyp:chrome_elf_unittests',
'../cloud_print/cloud_print.gyp:cloud_print_unittests',
@@ -1272,6 +1275,36 @@
}], # branding=="Chrome"
], # conditions
}], # OS="win"
['chromeos==1', {
'targets': [
{
'target_name': 'chromiumos_preflight',
'type': 'none',
'dependencies': [
'../breakpad/breakpad.gyp:minidump_stackwalk',
'../chrome/chrome.gyp:chrome',
'../chrome/chrome.gyp:chromedriver',
'../content/content_shell_and_tests.gyp:video_decode_accelerator_unittest',
'../content/content_shell_and_tests.gyp:video_encode_accelerator_unittest',
'../media/media.gyp:media_unittests',
'../ppapi/ppapi_internal.gyp:ppapi_example_video_decode',
'../sandbox/sandbox.gyp:chrome_sandbox',
'../sandbox/sandbox.gyp:sandbox_linux_unittests',
'../third_party/mesa/mesa.gyp:osmesa',
'../tools/telemetry/telemetry.gyp:bitmaptools#host',
'../tools/perf/clear_system_cache/clear_system_cache.gyp:clear_system_cache',
],
'conditions': [
['disable_nacl==0', {
'dependencies': [
'../components/nacl.gyp:nacl_helper',
'../native_client/src/trusted/service_runtime/linux/nacl_bootstrap.gyp:nacl_helper_bootstrap',
],
}],
],
},
], # targets
}], # "chromeos==1"
['use_aura==1', {
'targets': [
{
@@ -1387,7 +1420,7 @@
'target_name': 'chromoting_swarm_tests',
'type': 'none',
'dependencies': [
'../testing/chromoting/integration_tests.gyp:chromoting_integration_tests_run',
'../testing/chromoting/integration_tests.gyp:*',
],
}, # target_name: chromoting_swarm_tests
]

View File

@@ -0,0 +1,56 @@
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/config/android/rules.gni")
sun_tools_jar_path = "$root_gen_dir/sun_tools_jar/tools.jar"
action("find_sun_tools_jar") {
script = "//build/android/gyp/find_sun_tools_jar.py"
depfile = "$target_gen_dir/$target_name.d"
outputs = [
depfile,
sun_tools_jar_path,
]
args = [
"--depfile",
rebase_path(depfile, root_build_dir),
"--output",
rebase_path(sun_tools_jar_path, root_build_dir),
]
}
java_prebuilt("sun_tools_java") {
jar_path = sun_tools_jar_path
jar_dep = ":find_sun_tools_jar"
}
action("cpplib_stripped") {
_strip_bin = "${android_tool_prefix}strip"
_soname = "libc++_shared.so"
_input_so = "${android_libcpp_root}/libs/${android_app_abi}/${_soname}"
_output_so = "${root_out_dir}/lib.stripped/${_soname}"
script = "//build/gn_run_binary.py"
inputs = [
_strip_bin,
]
sources = [
_input_so,
]
outputs = [
_output_so,
]
_rebased_strip_bin = rebase_path(_strip_bin, root_out_dir)
_rebased_input_so = rebase_path(_input_so, root_out_dir)
_rebased_output_so = rebase_path(_output_so, root_out_dir)
args = [
_rebased_strip_bin,
"--strip-unneeded",
"-o",
_rebased_output_so,
_rebased_input_so,
]
}

View File

@@ -6,84 +6,109 @@
"""Utility script to install APKs from the command line quickly."""
import optparse
import argparse
import glob
import logging
import os
import sys
from pylib import constants
from pylib.device import device_blacklist
from pylib.device import device_errors
from pylib.device import device_utils
from pylib.utils import apk_helper
from pylib.utils import run_tests_helper
def AddInstallAPKOption(option_parser):
"""Adds apk option used to install the APK to the OptionParser."""
option_parser.add_option('--apk',
help=('DEPRECATED The name of the apk containing the'
' application (with the .apk extension).'))
option_parser.add_option('--apk_package',
help=('DEPRECATED The package name used by the apk '
'containing the application.'))
option_parser.add_option('--keep_data',
action='store_true',
default=False,
help=('Keep the package data when installing '
'the application.'))
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type',
default=os.environ.get('BUILDTYPE', 'Debug'),
help='If set, run test suites under out/Debug. '
def main():
parser = argparse.ArgumentParser()
apk_group = parser.add_mutually_exclusive_group(required=True)
apk_group.add_argument('--apk', dest='apk_name',
help='DEPRECATED The name of the apk containing the'
' application (with the .apk extension).')
apk_group.add_argument('apk_path', nargs='?',
help='The path to the APK to install.')
# TODO(jbudorick): Remove once no clients pass --apk_package
parser.add_argument('--apk_package', help='DEPRECATED unused')
parser.add_argument('--split',
action='append',
dest='splits',
help='A glob matching the apk splits. '
'Can be specified multiple times.')
parser.add_argument('--keep_data',
action='store_true',
default=False,
help='Keep the package data when installing '
'the application.')
parser.add_argument('--debug', action='store_const', const='Debug',
dest='build_type',
default=os.environ.get('BUILDTYPE', 'Debug'),
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
parser.add_argument('--release', action='store_const', const='Release',
dest='build_type',
help='If set, run test suites under out/Release. '
'Default is env var BUILDTYPE or Debug.')
option_parser.add_option('-d', '--device', dest='device',
help='Target device for apk to install on.')
parser.add_argument('-d', '--device', dest='device',
help='Target device for apk to install on.')
parser.add_argument('-v', '--verbose', action='count',
help='Enable verbose logging.')
args = parser.parse_args()
def ValidateInstallAPKOption(option_parser, options, args):
"""Validates the apk option and potentially qualifies the path."""
if not options.apk:
if len(args) > 1:
options.apk = args[1]
else:
option_parser.error('apk target not specified.')
run_tests_helper.SetLogLevel(args.verbose)
constants.SetBuildType(args.build_type)
if not options.apk.endswith('.apk'):
options.apk += '.apk'
apk = args.apk_path or args.apk_name
if not apk.endswith('.apk'):
apk += '.apk'
if not os.path.exists(apk):
apk = os.path.join(constants.GetOutDirectory(), 'apks', apk)
if not os.path.exists(apk):
parser.error('%s not found.' % apk)
if not os.path.exists(options.apk):
options.apk = os.path.join(constants.GetOutDirectory(), 'apks',
options.apk)
def main(argv):
parser = optparse.OptionParser()
parser.set_usage("usage: %prog [options] target")
AddInstallAPKOption(parser)
options, args = parser.parse_args(argv)
if len(args) > 1 and options.apk:
parser.error("Appending the apk as argument can't be used with --apk.")
elif len(args) > 2:
parser.error("Too many arguments.")
constants.SetBuildType(options.build_type)
ValidateInstallAPKOption(parser, options, args)
if args.splits:
splits = []
base_apk_package = apk_helper.ApkHelper(apk).GetPackageName()
for split_glob in args.splits:
apks = [f for f in glob.glob(split_glob) if f.endswith('.apk')]
if not apks:
logging.warning('No apks matched for %s.' % split_glob)
for f in apks:
helper = apk_helper.ApkHelper(f)
if (helper.GetPackageName() == base_apk_package
and helper.GetSplitName()):
splits.append(f)
devices = device_utils.DeviceUtils.HealthyDevices()
if options.device:
devices = [d for d in devices if d == options.device]
if args.device:
devices = [d for d in devices if d == args.device]
if not devices:
raise device_errors.DeviceUnreachableError(options.device)
raise device_errors.DeviceUnreachableError(args.device)
elif not devices:
raise device_errors.NoDevicesError()
device_utils.DeviceUtils.parallel(devices).Install(
options.apk, reinstall=options.keep_data)
def blacklisting_install(device):
try:
if args.splits:
device.InstallSplitApk(apk, splits, reinstall=args.keep_data)
else:
device.Install(apk, reinstall=args.keep_data)
except device_errors.CommandFailedError:
logging.exception('Failed to install %s', args.apk_name)
device_blacklist.ExtendBlacklist([str(device)])
logging.warning('Blacklisting %s', str(device))
except device_errors.CommandTimeoutError:
logging.exception('Timed out while installing %s', args.apk_name)
device_blacklist.ExtendBlacklist([str(device)])
logging.warning('Blacklisting %s', str(device))
device_utils.DeviceUtils.parallel(devices).pMap(blacklisting_install)
if __name__ == '__main__':
sys.exit(main(sys.argv))
sys.exit(main())

View File

@@ -23,28 +23,6 @@ sys.path.append(BUILD_ANDROID_DIR)
from pylib import constants
from pylib.utils import apk_helper
_DPI_TO_DENSITY = {
120: 'ldpi',
160: 'mdpi',
240: 'hdpi',
320: 'xhdpi',
480: 'xxhdpi',
}
def RetrieveDeviceConfig(device):
"""Probes the given device for its split-select config.
For example: en-rUS-xhdpi:armeabi-v7a
Run "split-select --help" for more info about the format.
"""
language = device.GetProp('persist.sys.language')
country = device.GetProp('persist.sys.country')
density_dpi = int(device.GetProp('ro.sf.lcd_density'))
density = _DPI_TO_DENSITY.get(density_dpi, 'tvdpi')
abi = device.product_cpu_abi
return '%s-r%s-%s:%s' % (language, country, density, abi)
def GetNewMetadata(device, apk_package):
"""Gets the metadata on the device for the apk_package apk."""
@@ -114,34 +92,10 @@ def main():
# the build, then the APK has to be installed (regardless of the md5 record).
force_install = HasInstallMetadataChanged(device, apk_package, metadata_path)
def SelectSplits(target_config, base_apk, split_apks, android_sdk_tools):
cmd = [os.path.join(android_sdk_tools, 'split-select'),
'--target', target_config,
'--base', base_apk,
]
for split in split_apks:
cmd.extend(('--split', split))
# split-select outputs one path per line and a blank line at the end.
output = build_utils.CheckOutput(cmd)
return [x for x in output.split('\n') if x]
def Install():
if options.split_apk_path:
requiredSdkVersion = constants.ANDROID_SDK_VERSION_CODES.LOLLIPOP
actualSdkVersion = device.device.build_version_sdk
if actualSdkVersion < requiredSdkVersion:
raise Exception(('--split-apk-path requires sdk version %s. Device has '
'version %s') % (requiredSdkVersion, actualSdkVersion))
device_config = RetrieveDeviceConfig(device.device)
active_splits = SelectSplits(
device_config,
options.apk_path,
options.split_apk_path,
options.android_sdk_tools)
all_apks = [options.apk_path] + active_splits
device.device.adb.InstallMultiple(all_apks, reinstall=True)
device.InstallSplitApk(options.apk_path, options.split_apk_path)
else:
device.Install(options.apk_path, reinstall=True)

View File

@@ -36,6 +36,7 @@ if os.getcwd() != self_dir:
java_args = [
"java",
"-classpath", ":".join(classpath),
"-enableassertions",
\"{main_class}\"] + sys.argv[1:]
os.execvp("java", java_args)
"""

View File

@@ -57,6 +57,7 @@ def main():
group = parser.add_argument_group('Test runner path arguments.')
group.add_argument('--output-directory')
group.add_argument('--isolate-file-path')
group.add_argument('--support-apk')
args, test_runner_args = parser.parse_known_args()
def RelativizePathToScript(path):
@@ -74,6 +75,9 @@ def main():
if args.isolate_file_path:
test_runner_path_args['--isolate-file-path'] = RelativizePathToScript(
args.isolate_file_path)
if args.support_apk:
test_runner_path_args['--support-apk'] = RelativizePathToScript(
args.support_apk)
with open(args.script_output_path, 'w') as script:
script.write(SCRIPT_TEMPLATE.format(

View File

@@ -28,7 +28,9 @@ def DoDex(options, paths):
input_paths=paths,
input_strings=dex_cmd,
force=not os.path.exists(options.dex_path))
build_utils.WriteJson(paths, options.dex_path + '.inputs')
build_utils.WriteJson(
[os.path.relpath(p, options.output_directory) for p in paths],
options.dex_path + '.inputs')
def main():
@@ -39,6 +41,9 @@ def main():
parser.add_option('--android-sdk-tools',
help='Android sdk build tools directory.')
parser.add_option('--output-directory',
default=os.getcwd(),
help='Path to the output build directory.')
parser.add_option('--dex-path', help='Dex output path.')
parser.add_option('--configuration-name',
help='The build CONFIGURATION_NAME.')
@@ -66,8 +71,10 @@ def main():
paths += build_utils.ParseGypList(options.inputs)
if options.excluded_paths:
# Excluded paths are relative to the output directory.
exclude_paths = build_utils.ParseGypList(options.excluded_paths)
paths = [p for p in paths if not p in exclude_paths]
paths = [p for p in paths if not
os.path.relpath(p, options.output_directory) in exclude_paths]
DoDex(options, paths)

View File

@@ -12,6 +12,7 @@ import optparse
import sys
import finalize_apk
from util import build_utils
def main():
parser = optparse.OptionParser()
@@ -25,20 +26,27 @@ def main():
parser.add_option('--key-name', help='Keystore name')
parser.add_option('--densities',
help='Comma separated list of densities finalize.')
parser.add_option('--languages',
help='GYP list of language splits to finalize.')
options, _ = parser.parse_args()
options.load_library_from_zip = 0
if options.densities:
for density in options.densities.split(','):
options.unsigned_apk_path = ("%s-%s" %
options.unsigned_apk_path = ("%s_%s" %
(options.resource_packaged_apk_path, density))
options.final_apk_path = ("%s-density-%s.apk" %
(options.base_output_path, density))
finalize_apk.FinalizeApk(options)
else:
raise Exception('Language splits not yet implemented')
if options.languages:
for lang in build_utils.ParseGypList(options.languages):
options.unsigned_apk_path = ("%s_%s" %
(options.resource_packaged_apk_path, lang))
options.final_apk_path = ("%s-lang-%s.apk" %
(options.base_output_path, lang))
finalize_apk.FinalizeApk(options)
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,56 @@
#!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This finds the java distribution's tools.jar and copies it somewhere.
"""
import argparse
import os
import re
import shutil
import sys
from util import build_utils
RT_JAR_FINDER = re.compile(r'\[Opened (.*)/jre/lib/rt.jar\]')
def main():
parser = argparse.ArgumentParser(description='Find Sun Tools Jar')
parser.add_argument('--depfile',
help='Path to depfile. This must be specified as the '
'action\'s first output.')
parser.add_argument('--output', required=True)
args = parser.parse_args()
sun_tools_jar_path = FindSunToolsJarPath()
if sun_tools_jar_path is None:
raise Exception("Couldn\'t find tools.jar")
# Using copyfile instead of copy() because copy() calls copymode()
# We don't want the locked mode because we may copy over this file again
shutil.copyfile(sun_tools_jar_path, args.output)
if args.depfile:
build_utils.WriteDepfile(
args.depfile,
[sun_tools_jar_path] + build_utils.GetPythonDependencies())
def FindSunToolsJarPath():
# This works with at least openjdk 1.6, 1.7 and sun java 1.6, 1.7
stdout = build_utils.CheckOutput(
["java", "-verbose", "-version"], print_stderr=False)
for ln in stdout.splitlines():
match = RT_JAR_FINDER.match(ln)
if match:
return os.path.join(match.group(1), 'lib', 'tools.jar')
return None
if __name__ == '__main__':
sys.exit(main())

View File

@@ -9,8 +9,8 @@ Given the manifest file for the main APK, generates an AndroidManifest.xml with
the value required for a Split APK (package, versionCode, etc).
"""
import lxml.etree
import optparse
import xml.etree.ElementTree
from util import build_utils
@@ -66,8 +66,8 @@ def Build(main_manifest, split, has_code):
The XML split manifest as a string
"""
doc = lxml.etree.fromstring(main_manifest)
package = doc.xpath('/manifest/@package')[0]
doc = xml.etree.ElementTree.fromstring(main_manifest)
package = doc.get('package')
return MANIFEST_TEMPLATE % {
'package': package,
@@ -90,7 +90,7 @@ def main():
if options.depfile:
build_utils.WriteDepfile(
options.depfile,
[main_manifest] + build_utils.GetPythonDependencies())
[options.main_manifest] + build_utils.GetPythonDependencies())
if __name__ == '__main__':

View File

@@ -38,18 +38,16 @@ def GetClassesInZipFile(zip_file):
def CallJavap(classpath, classes):
output = ''
for i in range(0, len(classes), 2000):
javap_cmd = [
'javap',
'-package', # Show public/protected/package.
# -verbose is required to get constant values (which can be inlined in
# dependents).
'-verbose',
'-classpath', classpath
] + classes[i:i+2000]
output += build_utils.CheckOutput(javap_cmd)
return output
javap_cmd = [
'javap',
'-package', # Show public/protected/package.
# -verbose is required to get constant values (which can be inlined in
# dependents).
'-verbose',
'-J-XX:NewSize=4m',
'-classpath', classpath
] + classes
return build_utils.CheckOutput(javap_cmd)
def ExtractToc(disassembled_classes):

View File

@@ -54,8 +54,20 @@ def ColorJavacOutput(output):
return '\n'.join(map(ApplyColor, output.split('\n')))
ERRORPRONE_OPTIONS = [
'-Xepdisable:'
# Something in chrome_private_java makes this check crash.
'com.google.errorprone.bugpatterns.ClassCanBeStatic,'
# These crash on lots of targets.
'com.google.errorprone.bugpatterns.WrongParameterPackage,'
'com.google.errorprone.bugpatterns.GuiceOverridesGuiceInjectableMethod,'
'com.google.errorprone.bugpatterns.GuiceOverridesJavaxInjectableMethod,'
'com.google.errorprone.bugpatterns.ElementsCountedInLoop'
]
def DoJavac(
classpath, classes_dir, chromium_code, java_files):
bootclasspath, classpath, classes_dir, chromium_code,
use_errorprone_path, java_files):
"""Runs javac.
Builds |java_files| with the provided |classpath| and puts the generated
@@ -75,10 +87,16 @@ def DoJavac(
# Chromium only allows UTF8 source files. Being explicit avoids
# javac pulling a default encoding from the user's environment.
'-encoding', 'UTF-8',
'-source', '1.7',
'-target', '1.7',
'-classpath', ':'.join(classpath),
'-d', classes_dir]
if bootclasspath:
javac_args.extend([
'-bootclasspath', ':'.join(bootclasspath),
'-source', '1.7',
'-target', '1.7',
])
if chromium_code:
# TODO(aurimas): re-enable '-Xlint:deprecation' checks once they are fixed.
javac_args.extend(['-Xlint:unchecked'])
@@ -88,7 +106,12 @@ def DoJavac(
# trigger a compile warning or error.
javac_args.extend(['-XDignore.symbol.file'])
javac_cmd = ['javac'] + javac_args + java_files
if use_errorprone_path:
javac_cmd = [use_errorprone_path] + ERRORPRONE_OPTIONS
else:
javac_cmd = ['javac']
javac_cmd = javac_cmd + javac_args + java_files
def Compile():
build_utils.CheckOutput(
@@ -163,6 +186,12 @@ def main(argv):
action='append',
default=[],
help='List of srcjars to include in compilation.')
parser.add_option(
'--bootclasspath',
action='append',
default=[],
help='Boot classpath for javac. If this is specified multiple times, '
'they will all be appended to construct the classpath.')
parser.add_option(
'--classpath',
action='append',
@@ -183,6 +212,10 @@ def main(argv):
help='Whether code being compiled should be built with stricter '
'warnings for chromium code.')
parser.add_option(
'--use-errorprone-path',
help='Use the Errorprone compiler at this path.')
parser.add_option(
'--classes-dir',
help='Directory for compiled .class files.')
@@ -202,6 +235,10 @@ def main(argv):
if options.main_class and not options.jar_path:
parser.error('--main-class requires --jar-path')
bootclasspath = []
for arg in options.bootclasspath:
bootclasspath += build_utils.ParseGypList(arg)
classpath = []
for arg in options.classpath:
classpath += build_utils.ParseGypList(arg)
@@ -215,7 +252,7 @@ def main(argv):
src_gendirs = build_utils.ParseGypList(options.src_gendirs)
java_files += build_utils.FindInDirectories(src_gendirs, '*.java')
input_files = classpath + java_srcjars + java_files
input_files = bootclasspath + classpath + java_srcjars + java_files
with build_utils.TempDir() as temp_dir:
classes_dir = os.path.join(temp_dir, 'classes')
os.makedirs(classes_dir)
@@ -238,9 +275,11 @@ def main(argv):
if len(java_files) != 0:
DoJavac(
bootclasspath,
classpath,
classes_dir,
options.chromium_code,
options.use_errorprone_path,
java_files)
if options.jar_path:

View File

@@ -20,8 +20,7 @@ _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
def _RunLint(lint_path, config_path, processed_config_path, manifest_path,
result_path, product_dir, sources, jar_path, resource_dir=None,
can_fail_build=False):
result_path, product_dir, sources, jar_path, resource_dir=None):
def _RelativizePath(path):
"""Returns relative path to top-level src dir.
@@ -122,7 +121,7 @@ def _RunLint(lint_path, config_path, processed_config_path, manifest_path,
if not os.path.exists(result_path):
print 'Something is wrong:'
print e
return 0
return 1
# There are actual lint issues
else:
@@ -133,7 +132,7 @@ def _RunLint(lint_path, config_path, processed_config_path, manifest_path,
print 'File contents:'
with open(result_path) as f:
print f.read()
return 0
return 1
_ProcessResultFile()
msg = ('\nLint found %d new issues.\n'
@@ -148,7 +147,7 @@ def _RunLint(lint_path, config_path, processed_config_path, manifest_path,
'lint', 'suppress.py')),
_RelativizePath(result_path)))
print >> sys.stderr, msg
return 1 if can_fail_build else 0
return 1
return 0
@@ -198,7 +197,7 @@ def main():
options.processed_config_path,
options.manifest_path, options.result_path,
options.product_dir, sources, options.jar_path,
options.resource_dir, options.can_fail_build)
options.resource_dir)
if options.depfile:
build_utils.WriteDepfile(
@@ -208,7 +207,7 @@ def main():
if options.stamp and not rc:
build_utils.Touch(options.stamp)
return rc
return rc if options.can_fail_build else 0
if __name__ == '__main__':

View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python
#
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Creates a resources.zip for locale .pak files.
Places the locale.pak files into appropriate resource configs
(e.g. en-GB.pak -> res/raw-en/en_gb.lpak). Also generates a locale_paks
TypedArray so that resource files can be enumerated at runtime.
"""
import collections
import optparse
import os
import sys
import zipfile
from util import build_utils
# This should stay in sync with:
# base/android/java/src/org/chromium/base/LocaleUtils.java
_CHROME_TO_ANDROID_LOCALE_MAP = {
'he': 'iw',
'id': 'in',
'fil': 'tl',
}
def ToResourceFileName(name):
"""Returns the resource-compatible file name for the given file."""
# Resources file names must consist of [a-z0-9_.].
# Changes extension to .lpak so that compression can be toggled separately for
# locale pak files vs other pak files.
return name.replace('-', '_').replace('.pak', '.lpak').lower()
def CreateLocalePaksXml(names):
"""Creates the contents for the locale-paks.xml files."""
VALUES_FILE_TEMPLATE = '''<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="locale_paks">%s
</array>
</resources>
'''
VALUES_ITEM_TEMPLATE = '''
<item>@raw/%s</item>'''
res_names = (os.path.splitext(name)[0] for name in names)
items = ''.join((VALUES_ITEM_TEMPLATE % name for name in res_names))
return VALUES_FILE_TEMPLATE % items
def ComputeMappings(sources):
"""Computes the mappings of sources -> resources.
Returns a tuple of:
- mappings: List of (src, dest) paths
- lang_to_locale_map: Map of language -> list of resource names
e.g. "en" -> ["en_gb.lpak"]
"""
lang_to_locale_map = collections.defaultdict(list)
mappings = []
for src_path in sources:
basename = os.path.basename(src_path)
name = os.path.splitext(basename)[0]
res_name = ToResourceFileName(basename)
if name == 'en-US':
dest_dir = 'raw'
else:
# Chrome's uses different region mapping logic from Android, so include
# all regions for each language.
android_locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(name, name)
lang = android_locale[0:2]
dest_dir = 'raw-' + lang
lang_to_locale_map[lang].append(res_name)
mappings.append((src_path, os.path.join(dest_dir, res_name)))
return mappings, lang_to_locale_map
def main():
parser = optparse.OptionParser()
build_utils.AddDepfileOption(parser)
parser.add_option('--locale-paks', help='List of files for res/raw-LOCALE')
parser.add_option('--resources-zip', help='Path to output resources.zip')
parser.add_option('--print-languages',
action='store_true',
help='Print out the list of languages that cover the given locale paks '
'(using Android\'s language codes)')
options, _ = parser.parse_args()
build_utils.CheckOptions(options, parser,
required=['locale_paks'])
sources = build_utils.ParseGypList(options.locale_paks)
if options.depfile:
deps = sources + build_utils.GetPythonDependencies()
build_utils.WriteDepfile(options.depfile, deps)
mappings, lang_to_locale_map = ComputeMappings(sources)
if options.print_languages:
print '\n'.join(sorted(lang_to_locale_map))
if options.resources_zip:
with zipfile.ZipFile(options.resources_zip, 'w', zipfile.ZIP_STORED) as out:
for mapping in mappings:
out.write(mapping[0], mapping[1])
# Create TypedArray resources so ResourceExtractor can enumerate files.
def WriteValuesFile(lang, names):
dest_dir = 'values'
if lang:
dest_dir += '-' + lang
# Always extract en-US.lpak since it's the fallback.
xml = CreateLocalePaksXml(names + ['en_us.lpak'])
out.writestr(os.path.join(dest_dir, 'locale-paks.xml'), xml)
for lang, names in lang_to_locale_map.iteritems():
WriteValuesFile(lang, names)
WriteValuesFile(None, [])
if __name__ == '__main__':
sys.exit(main())

View File

@@ -15,6 +15,7 @@ https://android.googlesource.com/platform/sdk/+/master/files/ant/build.xml
import optparse
import os
import re
import shutil
import zipfile
@@ -54,6 +55,14 @@ DENSITY_SPLITS = {
'ldrtl-sw600dp-xxhdpi-v17',
'xxhdpi-v21',
),
'xxxhdpi': (
'xxxhdpi-v4',
'ldrtl-xxxhdpi-v4',
'sw600dp-xxxhdpi-v13',
'ldrtl-xxxhdpi-v17',
'ldrtl-sw600dp-xxxhdpi-v17',
'xxxhdpi-v21',
),
'tvdpi': (
'tvdpi-v4',
'sw600dp-tvdpi-v13',
@@ -95,6 +104,8 @@ def ParseArgs():
'--create-density-splits',
action='store_true',
help='Enables density splits')
parser.add_option('--language-splits',
help='GYP list of languages to create splits for')
parser.add_option('--apk-path',
help='Path to output (partial) apk.')
@@ -165,23 +176,28 @@ def RenameDensitySplits(apk_path):
"""Renames all density splits to have shorter / predictable names."""
for density, config in DENSITY_SPLITS.iteritems():
src_path = '%s_%s' % (apk_path, '_'.join(config))
dst_path = '%s-%s' % (apk_path, density)
if os.path.exists(dst_path):
os.unlink(dst_path)
os.rename(src_path, dst_path)
dst_path = '%s_%s' % (apk_path, density)
if src_path != dst_path:
if os.path.exists(dst_path):
os.unlink(dst_path)
os.rename(src_path, dst_path)
def CheckDensityMissedConfigs(apk_path):
"""Raises an exception if apk_path contains any density-specifc files."""
triggers = ['-%s' % density for density in DENSITY_SPLITS]
def CheckForMissedConfigs(apk_path, check_density, languages):
"""Raises an exception if apk_path contains any unexpected configs."""
triggers = []
if check_density:
triggers.extend(re.compile('-%s' % density) for density in DENSITY_SPLITS)
if languages:
triggers.extend(re.compile(r'-%s\b' % lang) for lang in languages)
with zipfile.ZipFile(apk_path) as main_apk_zip:
for name in main_apk_zip.namelist():
for trigger in triggers:
if trigger in name and not 'mipmap-' in name:
raise Exception(('Found density in main apk that should have been ' +
if trigger.search(name) and not 'mipmap-' in name:
raise Exception(('Found config in main apk that should have been ' +
'put into a split: %s\nYou need to update ' +
'package_resources.py to include this new ' +
'config.') % name)
'config (trigger=%s)') % (name, trigger.pattern))
def main():
@@ -225,14 +241,23 @@ def main():
for config in DENSITY_SPLITS.itervalues():
package_command.extend(('--split', ','.join(config)))
language_splits = None
if options.language_splits:
language_splits = build_utils.ParseGypList(options.language_splits)
for lang in language_splits:
package_command.extend(('--split', lang))
if 'Debug' in options.configuration_name:
package_command += ['--debug-mode']
build_utils.CheckOutput(
package_command, print_stdout=False, print_stderr=False)
if options.create_density_splits or language_splits:
CheckForMissedConfigs(
options.apk_path, options.create_density_splits, language_splits)
if options.create_density_splits:
CheckDensityMissedConfigs(options.apk_path)
RenameDensitySplits(options.apk_path)
if options.depfile:

View File

@@ -42,6 +42,9 @@ class BuildDevice(object):
def Install(self, *args, **kwargs):
return self.device.Install(*args, **kwargs)
def InstallSplitApk(self, *args, **kwargs):
return self.device.InstallSplitApk(*args, **kwargs)
def GetInstallMetadata(self, apk_package):
"""Gets the metadata on the device for the apk_package apk."""
# Matches lines like:

View File

@@ -181,7 +181,8 @@ def main(argv):
possible_deps_config_paths = build_utils.ParseGypList(
options.possible_deps_configs)
allow_unknown_deps = options.type == 'android_apk'
allow_unknown_deps = (options.type == 'android_apk' or
options.type == 'android_resources')
unknown_deps = [
c for c in possible_deps_config_paths if not os.path.exists(c)]
if unknown_deps and not allow_unknown_deps:

View File

@@ -73,7 +73,7 @@ def GetDependencies(library_or_executable):
def GetNonSystemDependencies(library_name):
all_deps = GetDependencies(FullLibraryPath(library_name))
all_deps = GetDependencies(library_name)
return set((lib for lib in all_deps if not IsSystemLibrary(lib)))
@@ -119,8 +119,13 @@ def main():
java_libraries_list = (
'{%s}' % ','.join(['"%s"' % s[3:-3] for s in libraries]))
out_json = {
'libraries': libraries,
'lib_paths': [FullLibraryPath(l) for l in libraries],
'java_libraries_list': java_libraries_list
}
build_utils.WriteJson(
{'libraries': libraries, 'java_libraries_list': java_libraries_list},
out_json,
options.output,
only_if_changed=True)

View File

@@ -51,11 +51,16 @@ Still reading?
<ignore path="chrome/android/java/res/drawable-xxxhdpi"/>
<ignore path="ui/android/java/res/drawable-xxhdpi"/>
<ignore path="ui/android/java/res/drawable-xxxhdpi"/>
<ignore regexp=".*: reader_mode_bar_background.9.png, tabs_moved_htc.png, tabs_moved_nexus.png, tabs_moved_samsung.png$"/>
</issue>
<!-- It is OK for content_shell_apk and chrome_shell_apk to have missing assets. -->
<issue id="IconLocation">
<!-- It is OK for content_shell_apk and chrome_shell_apk to have missing assets. -->
<ignore path="content/shell/android/java/res/"/>
<ignore path="chrome/android/shell/res/"/>
<!-- Suppression for chrome/test/chromedriver/test/webview_shell/java/res/drawable/icon.png -->
<ignore path="res/drawable/icon.png"/>
<!-- TODO(lambroslambrou) remove this once crbug.com/502030 is fixed. -->
<ignore path="remoting/android/java/res"/>
</issue>
<issue id="InconsistentLayout" severity="ignore"/>
<issue id="InflateParams" severity="ignore"/>
@@ -72,6 +77,7 @@ Still reading?
<ignore path="org/chromium/base/SysUtils.class"/>
<ignore path="org/chromium/chrome/browser/TtsPlatformImpl.class"/>
<ignore path="org/chromium/chrome/browser/TtsPlatformImpl$*.class"/>
<ignore path="chrome/android/java/res/values-v17/styles.xml"/>
</issue>
<issue id="OldTargetApi">
<ignore path="AndroidManifest.xml"/>
@@ -87,11 +93,13 @@ Still reading?
</issue>
<issue id="SetJavaScriptEnabled" severity="ignore"/>
<issue id="UnusedResources">
<!--
TODO(pkotwicz): Re-enable after the chrome_java and chrome_staging_java
targets have been merged. crbug.com/484934
-->
<ignore path="chrome/android/java/res" />
<!-- Used by chrome/android/java/AndroidManifest.xml -->
<ignore path="chrome/android/java/res/drawable/window_background.xml" />
<ignore path="chrome/android/java/res/xml/bookmark_thumbnail_widget_info.xml" />
<ignore path="chrome/android/java/res/xml/file_paths.xml" />
<ignore path="content/shell/android/shell_apk/res/layout/content_shell_activity.xml" />
<ignore path="content/shell/android/shell_apk/res/values/strings.xml" />
</issue>
<issue id="SignatureOrSystemPermissions" severity="ignore"/>
<issue id="UnusedAttribute" severity="ignore"/>

View File

@@ -0,0 +1,55 @@
#! /usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import re
import sys
from pylib import constants
from pylib.sdk import dexdump
sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'util', 'lib',
'common'))
import perf_tests_results_helper
_METHOD_IDS_SIZE_RE = re.compile(r'^method_ids_size +: +(\d+)$')
def MethodCount(dexfile):
for line in dexdump.DexDump(dexfile, file_summary=True):
m = _METHOD_IDS_SIZE_RE.match(line)
if m:
return m.group(1)
raise Exception('"method_ids_size" not found in dex dump of %s' % dexfile)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--apk-name', help='Name of the APK to which the dexfile corresponds.')
parser.add_argument('dexfile')
args = parser.parse_args()
if not args.apk_name:
dirname, basename = os.path.split(args.dexfile)
while basename:
if 'apk' in basename:
args.apk_name = basename
break
dirname, basename = os.path.split(dirname)
else:
parser.error(
'Unable to determine apk name from %s, '
'and --apk-name was not provided.' % args.dexfile)
method_count = MethodCount(args.dexfile)
perf_tests_results_helper.PrintPerfResult(
'%s_methods' % args.apk_name, 'total', [method_count], 'methods')
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,90 @@
{
"lib_version": "7.3.0",
"clients": [
"play-services-base",
"play-services-cast",
"play-services-identity"
],
"client_filter": [
"res/drawable*",
"res/values-af",
"res/values-az",
"res/values-be",
"res/values-bn",
"res/values-bn-rBD",
"res/values-de-rAT",
"res/values-de-rCH",
"res/values-en-rIE",
"res/values-en-rIN",
"res/values-en-rSG",
"res/values-en-rZA",
"res/values-es-rAR",
"res/values-es-rBO",
"res/values-es-rCL",
"res/values-es-rCO",
"res/values-es-rCR",
"res/values-es-rDO",
"res/values-es-rEC",
"res/values-es-rGT",
"res/values-es-rHN",
"res/values-es-rMX",
"res/values-es-rNI",
"res/values-es-rPA",
"res/values-es-rPE",
"res/values-es-rPR",
"res/values-es-rPY",
"res/values-es-rSV",
"res/values-es-rUS",
"res/values-es-rUY",
"res/values-es-rVE",
"res/values-eu-rES",
"res/values-fr-rCA",
"res/values-fr-rCH",
"res/values-gl",
"res/values-gl-rES",
"res/values-gu",
"res/values-he",
"res/values-hy",
"res/values-hy-rAM",
"res/values-in",
"res/values-is",
"res/values-is-rIS",
"res/values-ka",
"res/values-ka-rGE",
"res/values-kk-rKZ",
"res/values-km",
"res/values-km-rKH",
"res/values-kn",
"res/values-kn-rIN",
"res/values-ky",
"res/values-ky-rKG",
"res/values-lo",
"res/values-lo-rLA",
"res/values-mk-rMK",
"res/values-ml",
"res/values-ml-rIN",
"res/values-mn",
"res/values-mn-rMN",
"res/values-mo",
"res/values-mr",
"res/values-mr-rIN",
"res/values-ms",
"res/values-ms-rMY",
"res/values-my-rMM",
"res/values-nb",
"res/values-ne",
"res/values-ne-rNP",
"res/values-si",
"res/values-si-rLK",
"res/values-ta",
"res/values-ta-rIN",
"res/values-te",
"res/values-te-rIN",
"res/values-tl",
"res/values-ur-rPK",
"res/values-uz-rUZ",
"res/values-zh",
"res/values-zh-rHK",
"res/values-zu"
]
}

View File

@@ -0,0 +1,238 @@
#!/usr/bin/env python
#
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Prepares the Google Play services split client libraries before usage by
Chrome's build system.
We need to preprocess Google Play services before using it in Chrome
builds for 2 main reasons:
- Getting rid of unused resources: unsupported languages, unused
drawables, etc.
- Merging the differents jars so that it can be proguarded more
easily. This is necessary since debug and test apks get very close
to the dex limit.
The script is supposed to be used with the maven repository that can be obtained
by downloading the "extra-google-m2repository" from the Android SDK Manager. It
also supports importing from already extracted AAR files using the
--is-extracted-repo flag.
The json config (see the -c argument) file should provide the following fields:
- lib_version: String. Used when building from the maven repository. It should
be the package's version (e.g. "7.3.0")
- clients: String array. List of clients to pick. For example, when building
from the maven repository, it's the artifactId (e.g. "play-services-base") of
each client.
- client_filter: String array. Pattern of files to prune from the clients once
extracted. Metacharacters are allowed. (e.g. "res/drawable*")
The output is a directory with the following structure:
OUT_DIR
+-- google-play-services.jar
+-- res
| +-- CLIENT_1
| | +-- color
| | +-- values
| | +-- etc.
| +-- CLIENT_2
| +-- ...
+-- stub
+-- res/[.git-keep-directory]
+-- src/android/UnusedStub.java
Requires the `jar` utility in the path.
'''
import argparse
import glob
import itertools
import json
import os
import shutil
import stat
import sys
from pylib import cmd_helper
from pylib import constants
sys.path.append(
os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'android', 'gyp'))
from util import build_utils
M2_PKG_PATH = os.path.join('com', 'google', 'android', 'gms')
def main():
parser = argparse.ArgumentParser(description=("Prepares the Google Play "
"services split client libraries before usage by Chrome's build system"))
parser.add_argument('-r',
'--repository',
help='The Google Play services repository location',
required=True,
metavar='FILE')
parser.add_argument('-o',
'--out-dir',
help='The output directory',
required=True,
metavar='FILE')
parser.add_argument('-c',
'--config-file',
help='Config file path',
required=True,
metavar='FILE')
parser.add_argument('-g',
'--git-friendly',
action='store_true',
default=False,
help='Add a .gitkeep file to the empty directories')
parser.add_argument('-x',
'--is-extracted-repo',
action='store_true',
default=False,
help='The provided repository is not made of AAR files.')
args = parser.parse_args()
ProcessGooglePlayServices(args.repository,
args.out_dir,
args.config_file,
args.git_friendly,
args.is_extracted_repo)
def ProcessGooglePlayServices(repo, out_dir, config_path, git_friendly,
is_extracted_repo):
with open(config_path, 'r') as json_file:
config = json.load(json_file)
with build_utils.TempDir() as tmp_root:
tmp_paths = _SetupTempDir(tmp_root)
if is_extracted_repo:
_ImportFromExtractedRepo(config, tmp_paths, repo)
else:
_ImportFromAars(config, tmp_paths, repo)
_GenerateCombinedJar(tmp_paths)
_ProcessResources(config, tmp_paths)
_BuildOutput(config, tmp_paths, out_dir, git_friendly)
def _SetupTempDir(tmp_root):
tmp_paths = {
'root': tmp_root,
'imported_clients': os.path.join(tmp_root, 'imported_clients'),
'extracted_jars': os.path.join(tmp_root, 'jar'),
'combined_jar': os.path.join(tmp_root, 'google-play-services.jar'),
}
os.mkdir(tmp_paths['imported_clients'])
os.mkdir(tmp_paths['extracted_jars'])
return tmp_paths
def _SetupOutputDir(out_dir):
out_paths = {
'root': out_dir,
'res': os.path.join(out_dir, 'res'),
'jar': os.path.join(out_dir, 'google-play-services.jar'),
'stub': os.path.join(out_dir, 'stub'),
}
shutil.rmtree(out_paths['jar'], ignore_errors=True)
shutil.rmtree(out_paths['res'], ignore_errors=True)
shutil.rmtree(out_paths['stub'], ignore_errors=True)
return out_paths
def _MakeWritable(dir_path):
for root, dirs, files in os.walk(dir_path):
for path in itertools.chain(dirs, files):
st = os.stat(os.path.join(root, path))
os.chmod(os.path.join(root, path), st.st_mode | stat.S_IWUSR)
def _ImportFromAars(config, tmp_paths, repo):
for client in config['clients']:
aar_name = '%s-%s.aar' % (client, config['lib_version'])
aar_path = os.path.join(repo, M2_PKG_PATH, client,
config['lib_version'], aar_name)
aar_out_path = os.path.join(tmp_paths['imported_clients'], client)
build_utils.ExtractAll(aar_path, aar_out_path)
client_jar_path = os.path.join(aar_out_path, 'classes.jar')
build_utils.ExtractAll(client_jar_path, tmp_paths['extracted_jars'],
no_clobber=False)
def _ImportFromExtractedRepo(config, tmp_paths, repo):
# Import the clients
try:
for client in config['clients']:
client_out_dir = os.path.join(tmp_paths['imported_clients'], client)
shutil.copytree(os.path.join(repo, client), client_out_dir)
client_jar_path = os.path.join(client_out_dir, 'classes.jar')
build_utils.ExtractAll(client_jar_path, tmp_paths['extracted_jars'],
no_clobber=False)
finally:
_MakeWritable(tmp_paths['imported_clients'])
def _GenerateCombinedJar(tmp_paths):
out_file_name = tmp_paths['combined_jar']
working_dir = tmp_paths['extracted_jars']
cmd_helper.Call(['jar', '-cf', out_file_name, '-C', working_dir, '.'])
def _ProcessResources(config, tmp_paths):
# Prune unused resources
for res_filter in config['client_filter']:
glob_pattern = os.path.join(tmp_paths['imported_clients'], '*', res_filter)
for prune_target in glob.glob(glob_pattern):
shutil.rmtree(prune_target)
def _BuildOutput(config, tmp_paths, out_dir, git_friendly):
out_paths = _SetupOutputDir(out_dir)
# Copy the resources to the output dir
for client in config['clients']:
res_in_tmp_dir = os.path.join(tmp_paths['imported_clients'], client, 'res')
if os.path.isdir(res_in_tmp_dir) and os.listdir(res_in_tmp_dir):
res_in_final_dir = os.path.join(out_paths['res'], client)
shutil.copytree(res_in_tmp_dir, res_in_final_dir)
# Copy the jar
shutil.copyfile(tmp_paths['combined_jar'], out_paths['jar'])
# Write the java dummy stub. Needed for gyp to create the resource jar
stub_location = os.path.join(out_paths['stub'], 'src', 'android')
os.makedirs(stub_location)
with open(os.path.join(stub_location, 'UnusedStub.java'), 'w') as stub:
stub.write('package android;'
'public final class UnusedStub {'
' private UnusedStub() {}'
'}')
# Create the main res directory. Will be empty but is needed by gyp
stub_res_location = os.path.join(out_paths['stub'], 'res')
os.makedirs(stub_res_location)
if git_friendly:
build_utils.Touch(os.path.join(stub_res_location, '.git-keep-directory'))
if __name__ == '__main__':
sys.exit(main())

View File

@@ -11,6 +11,7 @@ Usage:
"""
import argparse
import json
import logging
import os
import posixpath
@@ -61,6 +62,9 @@ def ProvisionDevices(options):
if options.auto_reconnect:
_LaunchHostHeartbeat()
blacklist = device_blacklist.ReadBlacklist()
if options.output_device_blacklist:
with open(options.output_device_blacklist, 'w') as f:
json.dump(blacklist, f)
if all(d in blacklist for d in devices):
raise device_errors.NoDevicesError
return 0
@@ -79,7 +83,11 @@ def ProvisionDevice(device, options):
return not options.phases or phase_name in options.phases
def run_phase(phase_func, reboot=True):
device.WaitUntilFullyBooted(timeout=reboot_timeout)
try:
device.WaitUntilFullyBooted(timeout=reboot_timeout, retries=0)
except device_errors.CommandTimeoutError:
logging.error('Device did not finish booting. Will try to reboot.')
device.Reboot(timeout=reboot_timeout)
phase_func(device, options)
if reboot:
device.Reboot(False, retries=0)
@@ -173,25 +181,19 @@ def SetProperties(device, options):
else:
device_settings.ConfigureContentSettings(
device, device_settings.ENABLE_LOCATION_SETTINGS)
if options.disable_mock_location:
device_settings.ConfigureContentSettings(
device, device_settings.DISABLE_MOCK_LOCATION_SETTINGS)
else:
device_settings.ConfigureContentSettings(
device, device_settings.ENABLE_MOCK_LOCATION_SETTINGS)
device_settings.SetLockScreenSettings(device)
if options.disable_network:
device_settings.ConfigureContentSettings(
device, device_settings.NETWORK_DISABLED_SETTINGS)
if options.min_battery_level is not None:
try:
battery = battery_utils.BatteryUtils(device)
battery.ChargeDeviceToLevel(options.min_battery_level)
except device_errors.CommandFailedError as e:
logging.exception('Unable to charge device to specified level.')
if options.max_battery_temp is not None:
try:
battery = battery_utils.BatteryUtils(device)
battery.LetBatteryCoolToTemperature(options.max_battery_temp)
except device_errors.CommandFailedError as e:
logging.exception('Unable to let battery cool to specified temperature.')
def _ConfigureLocalProperties(device, java_debug=True):
"""Set standard readonly testing device properties prior to reboot."""
local_props = [
@@ -218,6 +220,20 @@ def _ConfigureLocalProperties(device, java_debug=True):
def FinishProvisioning(device, options):
if options.min_battery_level is not None:
try:
battery = battery_utils.BatteryUtils(device)
battery.ChargeDeviceToLevel(options.min_battery_level)
except device_errors.CommandFailedError:
logging.exception('Unable to charge device to specified level.')
if options.max_battery_temp is not None:
try:
battery = battery_utils.BatteryUtils(device)
battery.LetBatteryCoolToTemperature(options.max_battery_temp)
except device_errors.CommandFailedError:
logging.exception('Unable to let battery cool to specified temperature.')
device.RunShellCommand(
['date', '-s', time.strftime('%Y%m%d.%H%M%S', time.gmtime())],
as_root=True, check_return=True)
@@ -301,6 +317,8 @@ def main():
' level before trying to continue')
parser.add_argument('--disable-location', action='store_true',
help='disable Google location services on devices')
parser.add_argument('--disable-mock-location', action='store_true',
default=False, help='Set ALLOW_MOCK_LOCATION to false')
parser.add_argument('--disable-network', action='store_true',
help='disable network access on devices')
parser.add_argument('--disable-java-debug', action='store_false',
@@ -317,6 +335,8 @@ def main():
help='Log more information.')
parser.add_argument('--max-battery-temp', type=int, metavar='NUM',
help='Wait for the battery to have this temp or lower.')
parser.add_argument('--output-device-blacklist',
help='Json file to output the device blacklist.')
args = parser.parse_args()
constants.SetBuildType(args.target)

View File

@@ -184,7 +184,7 @@ class ANDROID_SDK_VERSION_CODES(object):
LOLLIPOP_MR1 = 22
ANDROID_SDK_VERSION = ANDROID_SDK_VERSION_CODES.LOLLIPOP_MR1
ANDROID_SDK_BUILD_TOOLS_VERSION = '22.0.1'
ANDROID_SDK_BUILD_TOOLS_VERSION = '22.0.0'
ANDROID_SDK_ROOT = os.path.join(DIR_SOURCE_ROOT,
'third_party/android_tools/sdk')
ANDROID_SDK_TOOLS = os.path.join(ANDROID_SDK_ROOT,

View File

@@ -80,18 +80,16 @@ _DEVICE_PROFILES = [
'echo Connected > '
'/sys/bus/i2c/drivers/bq2419x/0-006b/input_cable_state && '
'dumpsys battery set ac 0 && dumpsys battery set usb 0'),
'charge_counter': (
'/sys/class/power_supply/max170xx_battery/charge_counter_ext'),
'voltage': '/sys/class/power_supply/max170xx_battery/voltage_now',
'current': '/sys/class/power_supply/max170xx_battery/current_now',
'charge_counter': '/sys/class/power_supply/battery/charge_counter_ext',
'voltage': '/sys/class/power_supply/battery/voltage_now',
'current': '/sys/class/power_supply/battery/current_now',
},
{
'name': 'Nexus 10',
'witness_file': None,
'enable_command': None,
'disable_command': None,
'charge_counter': (
'/sys/class/power_supply/ds2784-fuelgauge/charge_counter_ext'),
'charge_counter': None,
'voltage': '/sys/class/power_supply/ds2784-fuelgauge/voltage_now',
'current': '/sys/class/power_supply/ds2784-fuelgauge/current_now',

View File

@@ -38,6 +38,7 @@ public class Unzip {
s.println("unzip [zipfile]");
}
@SuppressWarnings("Finally")
private void unzip(String[] args) {
ZipInputStream zis = null;
try {

View File

@@ -949,7 +949,8 @@ class DeviceUtils(object):
for h, d in host_device_tuples:
if os.path.isdir(h):
self.RunShellCommand(['mkdir', '-p', d], check_return=True)
(changed_files, stale_files) = self._GetChangedAndStaleFiles(h, d)
changed_files, stale_files = (
self._GetChangedAndStaleFiles(h, d, delete_device_stale))
all_changed_files += changed_files
all_stale_files += stale_files
@@ -962,17 +963,19 @@ class DeviceUtils(object):
self._PushFilesImpl(host_device_tuples, all_changed_files)
def _GetChangedAndStaleFiles(self, host_path, device_path):
def _GetChangedAndStaleFiles(self, host_path, device_path, track_stale=False):
"""Get files to push and delete
Args:
host_path: an absolute path of a file or directory on the host
device_path: an absolute path of a file or directory on the device
track_stale: whether to bother looking for stale files (slower)
Returns:
a two-element tuple
1st element: a list of (host_files_path, device_files_path) tuples to push
2nd element: a list of stale files under device_path
2nd element: a list of stale files under device_path, or [] when
track_stale == False
"""
real_host_path = os.path.realpath(host_path)
try:
@@ -985,8 +988,13 @@ class DeviceUtils(object):
try:
host_checksums = md5sum.CalculateHostMd5Sums([real_host_path])
interesting_device_paths = [real_device_path]
if not track_stale and os.path.isdir(real_host_path):
interesting_device_paths = [
posixpath.join(real_device_path, os.path.relpath(p, real_host_path))
for p in host_checksums.keys()]
device_checksums = md5sum.CalculateDeviceMd5Sums(
[real_device_path], self)
interesting_device_paths, self)
except EnvironmentError as e:
logging.warning('Error calculating md5: %s', e)
return ([(host_path, device_path)], [])

View File

@@ -127,6 +127,18 @@ DISABLE_LOCATION_SETTINGS = [
]),
]
ENABLE_MOCK_LOCATION_SETTINGS = [
('settings/secure', [
('mock_location', 1),
]),
]
DISABLE_MOCK_LOCATION_SETTINGS = [
('settings/secure', [
('mock_location', 0),
]),
]
DETERMINISTIC_DEVICE_SETTINGS = [
('settings/global', [
('assisted_gps_enabled', 0),

View File

@@ -49,9 +49,6 @@ DownloadContentTest.ResumeWithDeletedFile
# http://crbug.com/386227
IndexedDBBrowserTest.VersionChangeCrashResilience
# http://crbug.com/386222
IndexedDBBrowserTest.DoesntHangTest
# http://crbug.com/233118
IndexedDBBrowserTest.NullKeyPathPersistence

View File

@@ -43,6 +43,11 @@ class TestPackageApk(TestPackage):
else:
self._package_info = constants.PACKAGE_INFO['gtest']
if suite_name == 'net_unittests':
self._extras = {'RunInSubThread': ''}
else:
self._extras = []
def _CreateCommandLineFileOnDevice(self, device, options):
device.WriteFile(self._package_info.cmdline_file,
self.suite_name + ' ' + options)
@@ -74,7 +79,8 @@ class TestPackageApk(TestPackage):
device.StartActivity(
intent.Intent(package=self._package_info.package,
activity=self._package_info.activity,
action='android.intent.action.MAIN'),
action='android.intent.action.MAIN',
extras=self._extras),
# No wait since the runner waits for FIFO creation anyway.
blocking=False,
force_stop=force_stop)

View File

@@ -16,6 +16,8 @@ class TestPackage(test_jar.TestJar):
if not os.path.exists(apk_path):
raise Exception('%s not found, please build it' % apk_path)
if test_support_apk_path and not os.path.exists(test_support_apk_path):
raise Exception('%s not found, please build it' % test_support_apk_path)
self._apk_path = apk_path
self._apk_name = os.path.splitext(os.path.basename(apk_path))[0]
self._package_name = apk_helper.GetPackageName(self._apk_path)

View File

@@ -18,4 +18,5 @@ PerfOptions = collections.namedtuple('PerfOptions', [
'collect_chartjson_data',
'output_chartjson_data',
'max_battery_temp',
'min_battery_level',
])

View File

@@ -277,6 +277,12 @@ class TestRunner(base_test_runner.BaseTestRunner):
self._device_battery.LetBatteryCoolToTemperature(
self._options.max_battery_temp)
logging.info('Charge level: %s%%',
str(self._device_battery.GetBatteryInfo().get('level')))
if self._options.min_battery_level:
self._device_battery.ChargeDeviceToLevel(
self._options.min_battery_level)
logging.info('%s : %s', test_name, cmd)
start_time = datetime.datetime.now()

View File

@@ -0,0 +1,42 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module wraps the Android Asset Packaging Tool."""
import os
from pylib import cmd_helper
from pylib import constants
from pylib.utils import timeout_retry
_AAPT_PATH = os.path.join(constants.ANDROID_SDK_TOOLS, 'aapt')
def _RunAaptCmd(args):
"""Runs an aapt command.
Args:
args: A list of arguments for aapt.
Returns:
The output of the command.
"""
cmd = [_AAPT_PATH] + args
status, output = cmd_helper.GetCmdStatusAndOutput(cmd)
if status != 0:
raise Exception('Failed running aapt command: "%s" with output "%s".' %
(' '.join(cmd), output))
return output
def Dump(what, apk, assets=None):
"""Returns the output of the aapt dump command.
Args:
what: What you want to dump.
apk: Path to apk you want to dump information for.
assets: List of assets in apk you want to dump information for.
"""
assets = assets or []
if isinstance(assets, basestring):
assets = [assets]
return _RunAaptCmd(['dump', what, apk] + assets).splitlines()

View File

@@ -3,7 +3,6 @@
# found in the LICENSE file.
"""This module wraps Android's split-select tool."""
# pylint: disable=unused-argument
import os
@@ -12,25 +11,21 @@ from pylib import constants
from pylib.utils import timeout_retry
_SPLIT_SELECT_PATH = os.path.join(constants.ANDROID_SDK_TOOLS, 'split-select')
_DEFAULT_TIMEOUT = 30
_DEFAULT_RETRIES = 2
def _RunSplitSelectCmd(args, timeout=None, retries=None):
def _RunSplitSelectCmd(args):
"""Runs a split-select command.
Args:
args: A list of arguments for split-select.
timeout: Timeout in seconds.
retries: Number of retries.
Returns:
The output of the command.
"""
cmd = [_SPLIT_SELECT_PATH] + args
status, output = cmd_helper.GetCmdStatusAndOutputWithTimeout(
cmd, timeout_retry.CurrentTimeoutThread().GetRemainingTime())
status, output = cmd_helper.GetCmdStatusAndOutput(cmd)
if status != 0:
raise Exception('Failed running command %s' % str(cmd))
raise Exception('Failed running command "%s" with output "%s".' %
(' '.join(cmd), output))
return output
def _SplitConfig(device):
@@ -45,16 +40,13 @@ def _SplitConfig(device):
device.screen_density,
device.product_cpu_abi))
def SelectSplits(device, base_apk, split_apks,
timeout=_DEFAULT_TIMEOUT, retries=_DEFAULT_RETRIES):
def SelectSplits(device, base_apk, split_apks):
"""Determines which APK splits the device requires.
Args:
device: A DeviceUtils object.
base_apk: The path of the base APK.
split_apks: A list of paths of APK splits.
timeout: Timeout in seconds.
retries: Number of retries.
Returns:
The list of APK splits that the device requires.
@@ -63,4 +55,4 @@ def SelectSplits(device, base_apk, split_apks,
args = ['--target', config, '--base', base_apk]
for split in split_apks:
args.extend(['--split', split])
return _RunSplitSelectCmd(args, timeout=timeout, retries=retries).splitlines()
return _RunSplitSelectCmd(args).splitlines()

View File

@@ -9,12 +9,15 @@ import re
from pylib import cmd_helper
from pylib import constants
from pylib.sdk import aapt
_AAPT_PATH = os.path.join(constants.ANDROID_SDK_TOOLS, 'aapt')
_MANIFEST_ATTRIBUTE_RE = re.compile(
r'\s*A: ([^\(\)= ]*)\([^\(\)= ]*\)="(.*)" \(Raw: .*\)$')
_MANIFEST_ELEMENT_RE = re.compile(r'\s*(?:E|N): (\S*) .*$')
_PACKAGE_NAME_RE = re.compile(r'package: .*name=\'(\S*)\'')
_SPLIT_NAME_RE = re.compile(r'package: .*split=\'(\S*)\'')
def GetPackageName(apk_path):
@@ -30,8 +33,7 @@ def GetInstrumentationName(apk_path):
def _ParseManifestFromApk(apk_path):
aapt_cmd = [_AAPT_PATH, 'dump', 'xmltree', apk_path, 'AndroidManifest.xml']
aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
aapt_output = aapt.Dump('xmltree', apk_path, 'AndroidManifest.xml')
parsed_manifest = {}
node_stack = [parsed_manifest]
@@ -70,6 +72,7 @@ class ApkHelper(object):
self._apk_path = apk_path
self._manifest = None
self._package_name = None
self._split_name = None
def GetActivityName(self):
"""Returns the name of the Activity in the apk."""
@@ -100,16 +103,27 @@ class ApkHelper(object):
if self._package_name:
return self._package_name
aapt_cmd = [_AAPT_PATH, 'dump', 'badging', self._apk_path]
aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
package_name_re = re.compile(r'package: .*name=\'(\S*)\'')
aapt_output = aapt.Dump('badging', self._apk_path)
for line in aapt_output:
m = package_name_re.match(line)
m = _PACKAGE_NAME_RE.match(line)
if m:
self._package_name = m.group(1)
return self._package_name
raise Exception('Failed to determine package name of %s' % self._apk_path)
def GetSplitName(self):
"""Returns the name of the split of the apk."""
if self._split_name:
return self._split_name
aapt_output = aapt.Dump('badging', self._apk_path)
for line in aapt_output:
m = _SPLIT_NAME_RE.match(line)
if m:
self._split_name = m.group(1)
return self._split_name
return None
def _GetManifest(self):
if not self._manifest:
self._manifest = _ParseManifestFromApk(self._apk_path)

View File

@@ -77,6 +77,35 @@
},
],
}, # build_output_dirs
{
'target_name': 'sun_tools_java',
'type': 'none',
'variables': {
'found_jar_path': '<(PRODUCT_DIR)/sun_tools_java/tools.jar',
'jar_path': '<(found_jar_path)',
},
'includes': [
'../../build/host_prebuilt_jar.gypi',
],
'actions': [
{
'action_name': 'find_sun_tools_jar',
'variables' : {
},
'inputs' : [
'gyp/find_sun_tools_jar.py',
'gyp/util/build_utils.py',
],
'outputs': [
'<(found_jar_path)',
],
'action': [
'python', 'gyp/find_sun_tools_jar.py',
'--output', '<(found_jar_path)',
],
},
],
}, # sun_tools_java
]
}

View File

@@ -332,6 +332,11 @@ def AddInstrumentationTestOptions(parser):
help=('The name of the apk containing the tests '
'(without the .apk extension; '
'e.g. "ContentShellTest").'))
group.add_argument('--support-apk', dest='test_support_apk_path',
help=('The path to an optional support apk to be '
'installed alongside the test apk. The '
'path should be relative to the output '
'directory (--output-directory).'))
group.add_argument('--coverage-dir',
help=('Directory in which to place all generated '
'EMMA coverage files.'))
@@ -379,8 +384,6 @@ def ProcessInstrumentationOptions(args):
constants.GetOutDirectory(),
constants.SDK_BUILD_TEST_JAVALIB_DIR,
'%s.jar' % args.test_apk)
args.test_support_apk_path = '%sSupport%s' % (
os.path.splitext(args.test_apk_path))
args.test_runner = apk_helper.GetInstrumentationName(args.test_apk_path)
@@ -613,6 +616,9 @@ def AddPerfTestOptions(parser):
'temperature (0.1 C)')
group.add_argument('single_step_command', nargs='*', action=SingleStepAction,
help='If --single-step is specified, the command to run.')
group.add_argument('--min-battery-level', type=int,
help='Only starts tests when the battery is charged above '
'given level.')
AddCommonOptions(parser)
AddDeviceOptions(parser)
@@ -635,7 +641,7 @@ def ProcessPerfTestOptions(args):
args.steps, args.flaky_steps, args.output_json_list,
args.print_step, args.no_timeout, args.test_filter,
args.dry_run, args.single_step, args.collect_chartjson_data,
args.output_chartjson_data, args.max_battery_temp)
args.output_chartjson_data, args.max_battery_temp, args.min_battery_level)
def AddPythonTestOptions(parser):

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2013 Google Inc.
-
- 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="dummy"
android:versionCode="1"
android:versionName="1.0">
<application android:label="dummy">
<activity android:name="dummy.DummyActivity"
android:label="dummy">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -1,34 +0,0 @@
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'multiple_proguards_test_apk',
'type': 'none',
'variables': {
'app_manifest_version_name%': '<(android_app_version_name)',
'java_in_dir': '.',
'proguard_enabled': 'true',
'proguard_flags_paths': [
# Both these proguard?.flags files need to be part of the build to
# remove both warnings from the src/dummy/DummyActivity.java file, else the
# build will fail.
'proguard1.flags',
'proguard2.flags',
],
'R_package': 'dummy',
'R_package_relpath': 'dummy',
'apk_name': 'MultipleProguards',
# This is a build-only test. There's nothing to install.
'gyp_managed_install': 0,
# The Java code produces warnings, so force the build to not show them.
'chromium_code': 0,
},
'includes': [ '../../../../build/java_apk.gypi' ],
},
],
}

View File

@@ -1 +0,0 @@
-dontwarn sun.misc.Unsafe

View File

@@ -1 +0,0 @@
-dontwarn sun.reflect.Reflection

View File

@@ -1,26 +0,0 @@
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dummy;
import android.app.Activity;
/**
* Dummy activity to build apk.
*
* This class is created to ensure that proguard will produce two separate warnings.
*/
public class DummyActivity extends Activity {
private static void doBadThings1() {
try {
sun.misc.Unsafe.getUnsafe();
} catch (Exception e) {
throw new Error(e);
}
}
private static void doBadThings2() {
sun.reflect.Reflection.getCallerClass(2);
}
}

View File

@@ -1,17 +0,0 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base.library_loader;
/**
* This is a complete dummy, required because base now requires a version of
* NativeLibraries to build, but doesn't include it in its jar file.
*/
public class NativeLibraries {
public static boolean sUseLinker = false;
public static boolean sUseLibraryInZipFile = false;
public static boolean sEnableLinkerTests = false;
static final String[] LIBRARIES = {};
static String sVersionNumber = "";
}

View File

@@ -49,7 +49,7 @@ def TestUpdate(device, old_apk, new_apk, app_data, package_name):
# Restore command is not synchronous
raw_input('Select "Restore my data" on the device. Then press enter to '
'continue.')
device_path = device.GetApplicationPath(package_name)
device_path = device.GetApplicationPaths(package_name)
if not device_path:
raise Exception('Expected package %s to already be installed. '
'Package name might have changed!' % package_name)

View File

@@ -3,6 +3,7 @@
"dir_name": "google",
"version": "21.0.0",
"zip": "google_google_play_services_21.0.0.zip",
"package": "google_play_services"
"package": "google_play_services",
"package_id": "extra-google-google_play_services"
}
]

View File

@@ -0,0 +1,131 @@
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Checks the status of an Android SDK package.
Verifies the given package has been installed from the Android SDK Manager and
that its version is at least the minimum version required by the project
configuration.
'''
import argparse
import json
import os
import re
import sys
COLORAMA_ROOT = os.path.join(os.path.dirname(__file__),
os.pardir, 'third_party', 'colorama', 'src')
sys.path.append(COLORAMA_ROOT)
import colorama
UDPATE_SCRIPT_PATH = 'build/install-android-sdks.sh'
SDK_EXTRAS_JSON_FILE = os.path.join(os.path.dirname(__file__),
'android_sdk_extras.json')
PACKAGE_VERSION_PATTERN = r'^Pkg\.Revision=(?P<version>\d+).*$'
PKG_NOT_FOUND_MSG = ('Error while checking Android SDK extras versions. '
'Could not find the "{package_id}" package in '
'{checked_location}. Please run {script} to download it.')
UPDATE_NEEDED_MSG = ('Error while checking Android SDK extras versions. '
'Version {minimum_version} or greater is required for the '
'package "{package_id}". Version {actual_version} found. '
'Please run {script} to update it.')
REQUIRED_VERSION_ERROR_MSG = ('Error while checking Android SDK extras '
'versions. '
'Could not retrieve the required version for '
'package "{package_id}".')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--package-id',
help=('id of the package to check for. The list of '
'available packages and their ids can be obtained '
'by running '
'third_party/android_tools/sdk/tools/android list '
'sdk --extended'))
parser.add_argument('--package-location',
help='path to the package\'s expected install location.',
metavar='DIR')
parser.add_argument('--stamp',
help=('if specified, a stamp file will be created at the '
'provided location.'),
metavar='FILE')
args = parser.parse_args()
if not ShouldSkipVersionCheck():
minimum_version = GetRequiredMinimumVersion(args.package_id)
CheckPackageVersion(args.package_id, args.package_location, minimum_version)
# Create the stamp file.
if args.stamp:
with open(args.stamp, 'a'):
os.utime(args.stamp, None)
sys.exit(0)
def ExitError(msg):
sys.exit(colorama.Fore.MAGENTA + colorama.Style.BRIGHT + msg +
colorama.Style.RESET_ALL)
def GetRequiredMinimumVersion(package_id):
with open(SDK_EXTRAS_JSON_FILE, 'r') as json_file:
packages = json.load(json_file)
for package in packages:
if package['package_id'] == package_id:
return int(package['version'].split('.')[0])
ExitError(REQUIRED_VERSION_ERROR_MSG.format(package_id=package_id))
def CheckPackageVersion(pkg_id, location, minimum_version):
version_file_path = os.path.join(location, 'source.properties')
# Extracts the version of the package described by the property file. We only
# care about the major version number here.
version_pattern = re.compile(PACKAGE_VERSION_PATTERN, re.MULTILINE)
if not os.path.isfile(version_file_path):
ExitError(PKG_NOT_FOUND_MSG.format(
package_id=pkg_id,
checked_location=location,
script=UDPATE_SCRIPT_PATH))
with open(version_file_path, 'r') as f:
match = version_pattern.search(f.read())
if not match:
ExitError(PKG_NOT_FOUND_MSG.format(
package_id=pkg_id,
checked_location=location,
script=UDPATE_SCRIPT_PATH))
pkg_version = int(match.group('version'))
if pkg_version < minimum_version:
ExitError(UPDATE_NEEDED_MSG.format(
package_id=pkg_id,
minimum_version=minimum_version,
actual_version=pkg_version,
script=UDPATE_SCRIPT_PATH))
# Everything looks ok, print nothing.
def ShouldSkipVersionCheck():
'''
Bots should not run the version check, since they download the sdk extras
in a different way.
'''
return bool(os.environ.get('CHROME_HEADLESS'))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This script provides methods for clobbering build directories."""
import argparse
import os
import shutil
import sys
def extract_gn_build_commands(build_ninja_file):
"""Extracts from a build.ninja the commands to run GN.
The commands to run GN are the gn rule and build.ninja build step at the
top of the build.ninja file. We want to keep these when deleting GN builds
since we want to preserve the command-line flags to GN.
On error, returns the empty string."""
result = ""
with open(build_ninja_file, 'r') as f:
# Read until the second blank line. The first thing GN writes to the file
# is the "rule gn" and the second is the section for "build build.ninja",
# separated by blank lines.
num_blank_lines = 0
while num_blank_lines < 2:
line = f.readline()
if len(line) == 0:
return '' # Unexpected EOF.
result += line
if line[0] == '\n':
num_blank_lines = num_blank_lines + 1
return result
def delete_build_dir(build_dir):
# GN writes a build.ninja.d file. Note that not all GN builds have args.gn.
build_ninja_d_file = os.path.join(build_dir, 'build.ninja.d')
if not os.path.exists(build_ninja_d_file):
shutil.rmtree(build_dir)
return
# GN builds aren't automatically regenerated when you sync. To avoid
# messing with the GN workflow, erase everything but the args file, and
# write a dummy build.ninja file that will automatically rerun GN the next
# time Ninja is run.
build_ninja_file = os.path.join(build_dir, 'build.ninja')
build_commands = extract_gn_build_commands(build_ninja_file)
try:
gn_args_file = os.path.join(build_dir, 'args.gn')
with open(gn_args_file, 'r') as f:
args_contents = f.read()
except IOError:
args_contents = ''
shutil.rmtree(build_dir)
# Put back the args file (if any).
os.mkdir(build_dir)
if args_contents != '':
with open(gn_args_file, 'w') as f:
f.write(args_contents)
# Write the build.ninja file sufficiently to regenerate itself.
with open(os.path.join(build_dir, 'build.ninja'), 'w') as f:
if build_commands != '':
f.write(build_commands)
else:
# Couldn't parse the build.ninja file, write a default thing.
f.write('''rule gn
command = gn -q gen //out/%s/
description = Regenerating ninja files
build build.ninja: gn
generator = 1
depfile = build.ninja.d
''' % (os.path.split(build_dir)[1]))
# Write a .d file for the build which references a nonexistant file. This
# will make Ninja always mark the build as dirty.
with open(build_ninja_d_file, 'w') as f:
f.write('build.ninja: nonexistant_file.gn\n')
def clobber(out_dir):
"""Clobber contents of build directory.
Don't delete the directory itself: some checkouts have the build directory
mounted."""
for f in os.listdir(out_dir):
path = os.path.join(out_dir, f)
if os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
delete_build_dir(path)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('out_dir', help='The output directory to clobber')
args = parser.parse_args()
clobber(args.out_dir)
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -80,6 +80,9 @@ config("feature_flags") {
if (enable_spellcheck) {
defines += [ "ENABLE_SPELLCHECK=1" ]
}
if (use_platform_spellchecker) {
defines += [ "USE_PLATFORM_SPELLCHECKER=1" ]
}
if (dont_embed_build_metadata) {
defines += [ "DONT_EMBED_BUILD_METADATA" ]
}
@@ -90,9 +93,6 @@ config("feature_flags") {
# TODO(brettw) should probably be "=1".
defines += [ "USE_UDEV" ]
}
if (toolkit_views) {
defines += [ "TOOLKIT_VIEWS=1" ]
}
if (ui_compositor_image_transport) {
# TODO(brettw) should probably be "=1".
defines += [ "UI_COMPOSITOR_IMAGE_TRANSPORT" ]
@@ -228,7 +228,7 @@ config("feature_flags") {
defines += [ "ENABLE_HIDPI=1" ]
}
if (enable_topchrome_md) {
defines += [ "ENABLE_TOPCHRME_MD=1" ]
defines += [ "ENABLE_TOPCHROME_MD=1" ]
}
if (proprietary_codecs) {
defines += [ "USE_PROPRIETARY_CODECS" ]
@@ -272,6 +272,9 @@ config("feature_flags") {
if (enable_media_router) {
defines += [ "ENABLE_MEDIA_ROUTER=1" ]
}
if (enable_webvr) {
defines += [ "ENABLE_WEBVR" ]
}
}
# Debug/release ----------------------------------------------------------------
@@ -396,3 +399,31 @@ config("default_libs") {
libs = [ "dl" ]
}
}
# Add this config to your target to enable precompiled headers.
#
# On Windows, precompiled headers are done on a per-target basis. If you have
# just a couple of files, the time it takes to precompile (~2 seconds) can
# actually be longer than the time saved. On a Z620, a 100 file target compiles
# about 2 seconds faster with precompiled headers, with greater savings for
# larger targets.
#
# Recommend precompiled headers for targets with more than 50 .cc files.
config("precompiled_headers") {
# TODO(brettw) enable this when GN support in the binary has been rolled.
#if (is_win) {
if (false) {
# This is a string rather than a file GN knows about. It has to match
# exactly what's in the /FI flag below, and what might appear in the source
# code in quotes for an #include directive.
precompiled_header = "build/precompile.h"
# This is a file that GN will compile with the above header. It will be
# implicitly added to the sources (potentially multiple times, with one
# variant for each language used in the target).
precompiled_source = "//build/precompile.cc"
# Force include the header.
cflags = [ "/FI$precompiled_header" ]
}
}

View File

@@ -2,6 +2,38 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# =============================================================================
# PLATFORM SELECTION
# =============================================================================
#
# There are two main things to set: "os" and "cpu". The "toolchain" is the name
# of the GN thing that encodes combinations of these things.
#
# Users typically only set the variables "target_os" and "target_cpu" in "gn
# args", the rest are set up by our build and internal to GN.
#
# There are three different types of each of these things: The "host"
# represents the computer doing the compile and never changes. The "target"
# represents the main thing we're trying to build. The "current" represents
# which configuration is currently being defined, which can be either the
# host, the target, or something completely different (like nacl). GN will
# run the same build file multiple times for the different required
# configuration in the same build.
#
# This gives the following variables:
# - host_os, host_cpu, host_toolchain
# - target_os, target_cpu, default_toolchain
# - current_os, current_cpu, current_toolchain.
#
# Note the default_toolchain isn't symmetrical (you would expect
# target_toolchain). This is because the "default" toolchain is a GN built-in
# concept, and "target" is something our build sets up that's symmetrical with
# its GYP counterpart. Potentially the built-in default_toolchain variable
# could be renamed in the future.
#
# When writing build files, to do something only for the host:
# if (current_toolchain == host_toolchain) { ...
if (target_os == "") {
target_os = host_os
}
@@ -101,18 +133,6 @@ declare_args() {
is_clang = current_os == "mac" || current_os == "ios" ||
current_os == "linux" || current_os == "chromeos"
# Selects the desired build flavor. Official builds get additional
# processing to prepare for release. Normally you will want to develop and
# test with this flag off.
# TODO(brettw) move to chrome_build.gni when DEPS are updated.
is_official_build = false
# Select the desired branding flavor. False means normal Chromium branding,
# true means official Google Chrome branding (requires extra Google-internal
# resources).
# TODO(brettw) move to chrome_build.gni when DEPS are updated.
is_chrome_branded = false
# Compile for Address Sanitizer to find memory bugs.
is_asan = false

View File

@@ -17,7 +17,7 @@ if (is_android) {
if (!defined(default_android_sdk_root)) {
default_android_sdk_root = "//third_party/android_tools/sdk"
default_android_sdk_version = "22"
default_android_sdk_build_tools_version = "22.0.1"
default_android_sdk_build_tools_version = "22.0.0"
}
if (!defined(google_play_services_library)) {
@@ -42,6 +42,9 @@ if (is_android) {
# Set to true to run findbugs on JAR targets.
run_findbugs = false
# Set to true to enable the Errorprone compiler
use_errorprone_java_compiler = false
}
# Host stuff -----------------------------------------------------------------
@@ -159,14 +162,19 @@ if (is_android) {
android_gdbserver =
"$android_ndk_root/prebuilt/$android_prebuilt_arch/gdbserver/gdbserver"
# libc++ stuff ---------------------------------------------------------------
# Toolchain stuff ------------------------------------------------------------
android_libcpp_root = "$android_ndk_root/sources/cxx-stl/llvm-libc++"
if (component_mode == "shared_library") {
android_libcpp_library = "c++_shared"
} else {
android_libcpp_library = "c++_static"
}
# By appending .cr, we prevent name collisions with libraries already
# loaded by the Android zygote.
android_product_extension = ".cr.so"
# ABI ------------------------------------------------------------------------
if (current_cpu == "x86") {

View File

@@ -86,6 +86,14 @@ template("findbugs") {
rebased_build_config = rebase_path(build_config, root_build_dir)
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.testonly)) {
testonly = invoker.testonly
}
inputs = [
"//build/android/pylib/utils/findbugs.py",
exclusions_file,
@@ -603,17 +611,26 @@ template("create_apk") {
_configuration_name = "Debug"
}
_create_density_splits =
defined(invoker.create_density_splits) && invoker.create_density_splits
if (_create_density_splits) {
_keystore_path = invoker.keystore_path
_keystore_name = invoker.keystore_name
_keystore_password = invoker.keystore_password
_split_densities = []
if (defined(invoker.create_density_splits) && invoker.create_density_splits) {
_split_densities = [
"hdpi",
"xhdpi",
"xxhdpi",
"xxxhdpi",
"tvdpi",
]
}
_split_languages = []
if (defined(invoker.language_splits)) {
_split_languages = invoker.language_splits
}
_package_resources_target_name = "${target_name}__package_resources"
action(_package_resources_target_name) {
deps = _package_deps
@@ -664,12 +681,24 @@ template("create_apk") {
if (_shared_resources) {
args += [ "--shared-resources" ]
}
if (_create_density_splits) {
if (_split_densities != []) {
args += [ "--create-density-splits" ]
foreach(_density, _split_densities) {
outputs += [ "${_resource_packaged_apk_path}-${_density}" ]
outputs += [ "${_resource_packaged_apk_path}_${_density}" ]
}
}
if (_split_languages != []) {
args += [ "--language-splits=$_split_languages" ]
foreach(_language, _split_languages) {
outputs += [ "${_resource_packaged_apk_path}_${_language}" ]
}
}
if (defined(invoker.extensions_to_not_compress)) {
args += [
"--no-compress",
invoker.extensions_to_not_compress,
]
}
}
package_target = "${target_name}__package"
@@ -736,9 +765,9 @@ template("create_apk") {
finalize_apk(_finalize_apk_rule_name) {
input_apk_path = _packaged_apk_path
output_apk_path = _final_apk_path
keystore_path = invoker.keystore_path
keystore_name = invoker.keystore_name
keystore_password = invoker.keystore_password
keystore_path = _keystore_path
keystore_name = _keystore_name
keystore_password = _keystore_password
rezip_apk = _load_library_from_apk
public_deps = [
@@ -749,23 +778,41 @@ template("create_apk") {
_final_deps = [ ":${_finalize_apk_rule_name}" ]
if (_create_density_splits) {
foreach(_density, _split_densities) {
_finalize_split_rule_name = "${target_name}__finalize_${_density}_split"
finalize_apk(_finalize_split_rule_name) {
input_apk_path = "${_resource_packaged_apk_path}-${_density}"
_output_paths = process_file_template(
[ _final_apk_path ],
"{{source_dir}}/{{source_name_part}}-${_density}.apk")
output_apk_path = _output_paths[0]
keystore_path = invoker.keystore_path
keystore_name = invoker.keystore_name
keystore_password = invoker.keystore_password
}
_final_deps += [ ":${_finalize_split_rule_name}" ]
template("finalize_split") {
finalize_apk(target_name) {
_config = invoker.split_config
_type = invoker.split_type
input_apk_path = "${_resource_packaged_apk_path}_${_config}"
_output_paths = process_file_template(
[ _final_apk_path ],
"{{source_dir}}/{{source_name_part}}-${_type}-${_config}.apk")
output_apk_path = _output_paths[0]
keystore_path = _keystore_path
keystore_name = _keystore_name
keystore_password = _keystore_password
deps = [
":${_package_resources_target_name}",
]
}
}
foreach(_split, _split_densities) {
_split_rule = "${target_name}__finalize_${_split}_split"
finalize_split(_split_rule) {
split_type = "density"
split_config = _split
}
_final_deps += [ ":$_split_rule" ]
}
foreach(_split, _split_languages) {
_split_rule = "${target_name}__finalize_${_split}_split"
finalize_split(_split_rule) {
split_type = "lang"
split_config = _split
}
_final_deps += [ ":$_split_rule" ]
}
group(target_name) {
public_deps = _final_deps
}
@@ -787,6 +834,14 @@ template("java_prebuilt_impl") {
if (_supports_android) {
_dex_path = _base_path + ".dex.jar"
}
_deps = []
if (defined(invoker.deps)) {
_deps = invoker.deps
}
_jar_deps = []
if (defined(invoker.jar_dep)) {
_jar_deps = [ invoker.jar_dep ]
}
_template_name = target_name
@@ -802,10 +857,7 @@ template("java_prebuilt_impl") {
requires_android =
defined(invoker.requires_android) && invoker.requires_android
deps = []
if (defined(invoker.deps)) {
deps += invoker.deps
}
deps = _deps
build_config = _build_config
jar_path = _jar_path
if (_supports_android) {
@@ -828,9 +880,7 @@ template("java_prebuilt_impl") {
input_jar_path = invoker.jar_path
output_jar_path = _jar_path
deps = [
":$build_config_target_name",
]
deps = [ ":$build_config_target_name" ] + _deps + _jar_deps
}
if (_supports_android) {
@@ -839,9 +889,7 @@ template("java_prebuilt_impl") {
_jar_path,
]
output = _dex_path
deps = [
":$process_jar_target_name",
]
deps = [ ":$process_jar_target_name" ] + _deps + _jar_deps
}
}
@@ -849,6 +897,9 @@ template("java_prebuilt_impl") {
deps = [
":$process_jar_target_name",
]
if (defined(invoker.data_deps)) {
data_deps = invoker.data_deps
}
if (_supports_android) {
deps += [ ":$dex_target_name" ]
}
@@ -895,6 +946,17 @@ template("compile_java") {
if (defined(invoker.chromium_code)) {
_chromium_code = invoker.chromium_code
}
_supports_android = true
if (defined(invoker.supports_android)) {
_supports_android = invoker.supports_android
}
_enable_errorprone = use_errorprone_java_compiler
if (defined(invoker.enable_errorprone)) {
_enable_errorprone = invoker.enable_errorprone
}
_manifest_entries = []
if (defined(invoker.manifest_entries)) {
_manifest_entries = invoker.manifest_entries
@@ -958,13 +1020,23 @@ template("compile_java") {
"--java-srcjars=@FileArg($_rebased_build_config:javac:srcjars)",
"--jar-excluded-classes=$_jar_excluded_patterns",
]
if (_supports_android) {
_rebased_android_sdk_jar = rebase_path(android_sdk_jar, root_build_dir)
args += [ "--bootclasspath=$_rebased_android_sdk_jar" ]
}
foreach(e, _manifest_entries) {
args += [ "--manifest-entry=" + e ]
}
if (_chromium_code) {
args += [ "--chromium-code=1" ]
}
if (_enable_errorprone) {
deps += [ "//third_party/errorprone:chromium_errorprone" ]
args += [
"--use-errorprone-path",
"bin/chromium_errorprone",
]
}
args += rebase_path(_java_files, root_build_dir)
}
@@ -1114,6 +1186,9 @@ template("java_library_impl") {
chromium_code = _chromium_code
android = _requires_android
if (defined(invoker.enable_errorprone)) {
enable_errorprone = invoker.enable_errorprone
}
if (defined(invoker.jar_excluded_patterns)) {
jar_excluded_patterns = invoker.jar_excluded_patterns
}
@@ -1130,6 +1205,7 @@ template("java_library_impl") {
manifest_entries = invoker.manifest_entries
}
supports_android = _supports_android
deps = build_config_deps
}
@@ -1414,6 +1490,9 @@ template("generate_split_manifest") {
action(target_name) {
depfile = "$target_gen_dir/$target_name.d"
if (defined(invoker.deps)) {
deps = invoker.deps
}
args = [
"--main-manifest",
rebase_path(invoker.main_manifest, root_build_dir),
@@ -1484,6 +1563,12 @@ template("test_runner_script") {
"--test-apk",
invoker.test_apk,
]
if (defined(invoker.support_apk_path)) {
test_runner_args += [
"--support-apk",
rebase_path(invoker.support_apk_path, root_build_dir),
]
}
} else {
assert(false, "Invalid test type: $_test_type.")
}

View File

@@ -544,6 +544,69 @@ template("jinja_template_resources") {
}
}
# Creates a resources.zip with locale.pak files placed into appropriate
# resource configs (e.g. en-GB.pak -> res/raw-en/en_gb.pak). Also generates
# a locale_paks TypedArray so that resource files can be enumerated at runtime.
#
# If this target is included in the deps of an android resources/library/apk,
# the resources will be included with that target.
#
# Variables:
# sources: List of .pak files. Names must be of the form "en.pak" or
# "en-US.pak".
# deps: (optional) List of dependencies that might be needed to generate
# the .pak files.
#
# Example
# locale_pak_resources("locale_paks") {
# sources = [ "path/en-US.pak", "path/fr.pak", ... ]
# }
template("locale_pak_resources") {
set_sources_assignment_filter([])
assert(defined(invoker.sources))
_base_path = "$target_gen_dir/$target_name"
_resources_zip = _base_path + ".resources.zip"
_build_config = _base_path + ".build_config"
write_build_config("${target_name}__build_config") {
build_config = _build_config
resources_zip = _resources_zip
type = "android_resources"
}
action("${target_name}__create_resources_zip") {
sources = invoker.sources
script = "//build/android/gyp/locale_pak_resources.py"
depfile = "$target_gen_dir/$target_name.d"
outputs = [
depfile,
_resources_zip,
]
_rebased_sources = rebase_path(invoker.sources, root_build_dir)
args = [
"--locale-paks=${_rebased_sources}",
"--resources-zip",
rebase_path(_resources_zip, root_build_dir),
"--depfile",
rebase_path(depfile, root_build_dir),
]
if (defined(invoker.deps)) {
deps = invoker.deps
}
}
group(target_name) {
deps = [
":${target_name}__build_config",
":${target_name}__create_resources_zip",
]
}
}
# Declare an Android resources target
#
# This creates a resources zip file that will be used when building an Android
@@ -798,6 +861,7 @@ template("java_strings_grd_prebuilt") {
# android_library target, for example.
#
# chromium_code: If true, extra analysis warning/errors will be enabled.
# enable_errorprone: If true, enables the errorprone compiler.
#
# data_deps, testonly
#
@@ -825,6 +889,9 @@ template("java_binary") {
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.enable_errorprone)) {
enable_errorprone = invoker.enable_errorprone
}
if (defined(invoker.java_files)) {
java_files = invoker.java_files
}
@@ -841,6 +908,7 @@ template("java_binary") {
testonly = invoker.testonly
}
supports_android = false
main_class = invoker.main_class
}
}
@@ -919,6 +987,8 @@ template("junit_binary") {
# ease the gyp->gn conversion and will be removed in the future.
#
# chromium_code: If true, extra analysis warning/errors will be enabled.
# enable_errorprone: If true, enables the errorprone compiler.
#
# jar_excluded_patterns: List of patterns of .class files to exclude from the
# final jar.
#
@@ -967,6 +1037,9 @@ template("java_library") {
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.enable_errorprone)) {
enable_errorprone = invoker.enable_errorprone
}
if (defined(invoker.jar_excluded_patterns)) {
jar_excluded_patterns = invoker.jar_excluded_patterns
}
@@ -1007,6 +1080,7 @@ template("java_library") {
# deps: Specifies the dependencies of this target. Java targets in this list
# will be added to the javac classpath.
# jar_path: Path to the prebuilt jar.
# jar_dep: Target that builds jar_path (optional).
# proguard_preprocess: If true, proguard preprocessing will be run. This can
# be used to remove unwanted parts of the library.
# proguard_config: Path to the proguard config for preprocessing.
@@ -1023,12 +1097,18 @@ template("java_prebuilt") {
set_sources_assignment_filter([])
java_prebuilt_impl(target_name) {
jar_path = invoker.jar_path
if (defined(invoker.jar_dep)) {
jar_dep = invoker.jar_dep
}
if (defined(invoker.testonly)) {
testonly = invoker.testonly
}
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.data_deps)) {
data_deps = invoker.data_deps
}
if (defined(invoker.proguard_config)) {
proguard_config = invoker.proguard_config
}
@@ -1058,6 +1138,8 @@ template("java_prebuilt") {
# ease the gyp->gn conversion and will be removed in the future.
#
# chromium_code: If true, extra analysis warning/errors will be enabled.
# enable_errorprone: If true, enables the errorprone compiler.
#
# jar_excluded_patterns: List of patterns of .class files to exclude from the
# final jar.
#
@@ -1103,6 +1185,9 @@ template("android_library") {
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.enable_errorprone)) {
enable_errorprone = invoker.enable_errorprone
}
if (defined(invoker.jar_excluded_patterns)) {
jar_excluded_patterns = invoker.jar_excluded_patterns
}
@@ -1201,6 +1286,9 @@ template("android_java_prebuilt") {
if (defined(invoker.deps)) {
deps = invoker.deps
}
if (defined(invoker.data_deps)) {
data_deps = invoker.data_deps
}
if (defined(invoker.proguard_config)) {
proguard_config = invoker.proguard_config
}
@@ -1217,6 +1305,7 @@ template("android_java_prebuilt") {
#
# Variables
# android_manifest: Path to AndroidManifest.xml.
# android_manifest_dep: Target that generates AndroidManifest (if applicable)
# data_deps: List of dependencies needed at runtime. These will be built but
# won't change the generated .apk in any way (in fact they may be built
# after the .apk is).
@@ -1348,15 +1437,22 @@ template("android_apk") {
"Relocation packing requires use of the" + " Chromium linker.")
}
_native_libs = process_file_template(
invoker.native_libs,
"$root_build_dir/lib.stripped/{{source_file_part}}")
if (is_component_build) {
_native_libs += [ "$root_out_dir/lib.stripped/libc++_shared.so" ]
_chromium_linker_dep += [ "//build/android:cpplib_stripped" ]
}
# Allow native_libs to be in the form "foo.so" or "foo.cr.so"
_first_ext_removed =
process_file_template(invoker.native_libs, "{{source_name_part}}")
_native_libs += process_file_template(
_first_ext_removed,
"$root_build_dir/lib.stripped/{{source_name_part}}$android_product_extension")
_native_libs_dir = base_path + "/libs"
if (_use_chromium_linker) {
_native_libs +=
[ "$root_build_dir/lib.stripped/libchromium_android_linker.so" ]
_native_libs += [ "$root_build_dir/lib.stripped/libchromium_android_linker$android_product_extension" ]
}
_enable_relocation_packing = false
@@ -1365,13 +1461,22 @@ template("android_apk") {
_enable_relocation_packing = true
}
_native_lib_version_name = ""
if (defined(invoker.native_lib_version_name)) {
_native_lib_version_name = invoker.native_lib_version_name
_native_lib_version_rule = ""
if (defined(invoker.native_lib_version_rule)) {
_native_lib_version_rule = invoker.native_lib_version_rule
}
_native_lib_version_arg = "\"\""
if (defined(invoker.native_lib_version_arg)) {
_native_lib_version_arg = invoker.native_lib_version_arg
}
}
_android_manifest_deps = []
if (defined(invoker.android_manifest_dep)) {
_android_manifest_deps = [ invoker.android_manifest_dep ]
}
_android_manifest = invoker.android_manifest
_rebased_build_config = rebase_path(_build_config, root_build_dir)
_create_abi_split =
defined(invoker.create_abi_split) && invoker.create_abi_split
@@ -1389,7 +1494,7 @@ template("android_apk") {
build_config = _build_config
android_manifest = _android_manifest
deps = _chromium_linker_dep
deps = _chromium_linker_dep + _android_manifest_deps
if (defined(invoker.deps)) {
deps += invoker.deps
}
@@ -1419,9 +1524,7 @@ template("android_apk") {
}
build_config = _build_config
deps = [
":$build_config_target",
]
deps = _android_manifest_deps + [ ":$build_config_target" ]
if (defined(invoker.deps)) {
deps += invoker.deps
}
@@ -1445,11 +1548,14 @@ template("android_apk") {
deps = [
":$build_config_target",
]
if (_native_lib_version_rule != "") {
deps += [ _native_lib_version_rule ]
}
defines = [
"NATIVE_LIBRARIES_LIST=" +
"@FileArg($_rebased_build_config:native:java_libraries_list)",
"NATIVE_LIBRARIES_VERSION_NUMBER=\"$_native_lib_version_name\"",
"NATIVE_LIBRARIES_VERSION_NUMBER=$_native_lib_version_arg",
]
if (_use_chromium_linker) {
defines += [ "ENABLE_CHROMIUM_LINKER" ]
@@ -1470,9 +1576,7 @@ template("android_apk") {
supports_android = true
requires_android = true
override_build_config = _build_config
deps = [
":$build_config_target",
]
deps = _android_manifest_deps + [ ":$build_config_target" ]
android_manifest = _android_manifest
chromium_code = true
@@ -1544,7 +1648,7 @@ template("android_apk") {
if (_native_libs != []) {
action("${_template_name}__prepare_native") {
script = "//build/android/gyp/pack_arm_relocations.py"
script = "//build/android/gyp/pack_relocations.py"
packed_libraries_dir = "$_native_libs_dir/$android_app_abi"
depfile = "$target_gen_dir/$target_name.d"
outputs = [
@@ -1559,7 +1663,7 @@ template("android_apk") {
skip_packing_list = [
"gdbserver",
"libchromium_android_linker.so",
"libchromium_android_linker$android_product_extension",
]
enable_packing_arg = 0
@@ -1609,6 +1713,17 @@ template("android_apk") {
dex_path = final_dex_path
load_library_from_apk = _load_library_from_apk
create_density_splits = _create_density_splits
if (defined(invoker.language_splits)) {
language_splits = invoker.language_splits
}
if (defined(invoker.extensions_to_not_compress)) {
extensions_to_not_compress = invoker.extensions_to_not_compress
} else {
# Allow icu data, v8 snapshots, and pak files to be loaded directly from
# the .apk.
# Note: These are actually suffix matches, not necessarily extensions.
extensions_to_not_compress = ".dat,.bin,.pak"
}
version_code = _version_code
version_name = _version_name
@@ -1618,10 +1733,10 @@ template("android_apk") {
keystore_password = _keystore_password
# This target generates the input file _all_resources_zip_path.
deps = [
":$process_resources_target",
":$final_dex_target_name",
]
deps = _android_manifest_deps + [
":$process_resources_target",
":$final_dex_target_name",
]
if (defined(invoker.deps)) {
deps += invoker.deps
}
@@ -1650,6 +1765,7 @@ template("android_apk") {
out_manifest =
"$gen_dir/split-manifests/${android_app_abi}/AndroidManifest.xml"
split_name = "abi_${android_app_abi}"
deps = _android_manifest_deps
}
_apk_rule = "${_template_name}__split_apk_abi_${android_app_abi}"
@@ -1675,6 +1791,7 @@ template("android_apk") {
native_libs_dir = _native_libs_dir
deps = [
":${_template_name}__prepare_native",
":${_manifest_rule}",
]
}
}
@@ -1705,6 +1822,9 @@ template("android_apk") {
# srcjar_deps: List of srcjar dependencies. The .java files in the srcjars
# will be added to java_files and be included in this apk.
# apk_name: Name for final apk.
# support_apk_path: Path to a support apk. If present, the test runner script
# will install it on the device before running the instrumentation tests.
# Should be a path relative to the src root.
# final_apk_path: Path to final built apk. Default is
# $root_out_dir/apks/$apk_name.apk. Setting this will override apk_name.
# native_libs: List paths of native libraries to include in this apk. If these
@@ -1744,6 +1864,9 @@ template("instrumentation_test_apk") {
if (defined(invoker.isolate_file)) {
isolate_file = invoker.isolate_file
}
if (defined(invoker.support_apk_path)) {
support_apk_path = invoker.support_apk_path
}
}
}
@@ -1830,7 +1953,7 @@ template("unittest_apk") {
if (defined(invoker.unittests_binary)) {
unittests_binary = invoker.unittests_binary
} else {
unittests_binary = "lib" + test_suite_name + ".so"
unittests_binary = "lib${test_suite_name}${android_product_extension}"
}
if (defined(invoker.apk_name)) {
@@ -1856,6 +1979,7 @@ template("unittest_apk") {
"//base:base_java",
"//build/android/pylib/remote/device/dummy:remote_device_dummy_apk",
"//testing/android/appurify_support:appurify_support_java",
"//testing/android/reporter:reporter_java",
]
if (defined(invoker.deps)) {
deps += invoker.deps
@@ -1979,11 +2103,6 @@ template("create_native_executable_dist") {
libraries_list =
"${target_gen_dir}/${template_name}_library_dependencies.list"
# TODO(gyp)
#'dependencies': [
#'<(DEPTH)/build/android/setup.gyp:copy_system_libraries',
#],
find_deps_target_name = "${template_name}__find_library_dependencies"
copy_target_name = "${template_name}__copy_libraries_and_exe"
@@ -2031,7 +2150,7 @@ template("create_native_executable_dist") {
rebased_libraries_list = rebase_path(libraries_list, root_build_dir)
args = [
"--files=$rebased_binaries_list",
"--files=@FileArg($rebased_libraries_list:libraries)",
"--files=@FileArg($rebased_libraries_list:lib_paths)",
]
deps = [

View File

@@ -6,17 +6,14 @@ declare_args() {
# Selects the desired build flavor. Official builds get additional
# processing to prepare for release. Normally you will want to develop and
# test with this flag off.
# TODO(brettw) move here from BUILDCONFIG.gn when DEPS are updated.
#is_official_build = false
is_official_build = false
# Select the desired branding flavor. False means normal Chromium branding,
# true means official Google Chrome branding (requires extra Google-internal
# resources).
# TODO(brettw) move here from BUILDCONFIG.gn when DEPS are updated.
#is_chrome_branded = false
is_chrome_branded = false
# Break chrome.dll into multple pieces based on process type. Only available
# on Windows.
# TODO(brettw) make this work. When it does, the declaration should be:
is_multi_dll_chrome = is_win && !is_component_build
}

View File

@@ -13,6 +13,9 @@ if (current_cpu == "mipsel" || current_cpu == "mips64el") {
if (is_posix) {
import("//build/config/gcc/gcc_version.gni")
}
if (is_win) {
import("//build/config/win/visual_studio_version.gni")
}
import("//build/toolchain/ccache.gni")
import("//build/config/sanitizers/sanitizers.gni")
@@ -48,8 +51,8 @@ declare_args() {
# with some utilities such as icecc and ccache. Requires gold and
# gcc >= 4.8 or clang.
# http://gcc.gnu.org/wiki/DebugFission
use_debug_fission =
!is_win && use_gold && linux_use_bundled_binutils && !use_ccache
use_debug_fission = is_debug && !is_win && use_gold &&
linux_use_bundled_binutils && !use_ccache
if (is_win) {
# Whether the VS xtree header has been patched to disable warning 4702. If
@@ -127,6 +130,14 @@ config("compiler") {
} else {
cflags += [ "-m64" ]
}
if (exec_script("//build/win/use_ansi_codes.py", [], "trim string") ==
"True") {
cflags += [
# cmd.exe doesn't understand ANSI escape codes by default,
# so only enable them if something emulating them is around.
"-fansi-escape-codes",
]
}
}
} else {
# Common GCC compiler flags setup.
@@ -405,13 +416,6 @@ config("compiler") {
} else {
cflags += [ "-funwind-tables" ]
}
if (is_clang && !is_nacl && !is_debug) {
# Non-unique section names appears to make linker dead stripping
# less effective. See http://crbug.com/483026#c20
# TODO(hans): Remove this if resolved upstream.
cflags += [ "-funique-section-names" ]
}
}
# Linux/Android common flags setup.
@@ -463,17 +467,7 @@ config("compiler") {
if (!is_asan && !is_msan && !is_lsan && !is_tsan) {
# TODO(brettw) common.gypi has this only for target toolset.
if (current_cpu == "x64") {
# --icf=safe disables much more folding on x86_64 than elsewhere, see
# http://crbug.com/492177. Turning it on saves over 12 MB of binary
# size, but it seems to regress cold startup time by over a second
# (see http://crbug.com/492809).
# TODO(thakis): Check if disabling ICF would inmprove android cold start
# times by several seconds too.
ldflags += [ "-Wl,--icf=safe" ]
} else {
ldflags += [ "-Wl,--icf=all" ]
}
ldflags += [ "-Wl,--icf=all" ]
}
# TODO(thestig): Make this flag work with GN.
@@ -657,8 +651,6 @@ config("runtime_library") {
# arm-linux-androideabi-4.4.3 toolchain (circa Gingerbread) will exhibit
# strange errors. The include ordering here is important; change with
# caution.
android_libcpp_root = "$android_ndk_root/sources/cxx-stl/llvm-libc++"
cflags += [
"-isystem" +
rebase_path("$android_libcpp_root/libcxx/include", root_build_dir),
@@ -671,13 +663,6 @@ config("runtime_library") {
]
lib_dirs += [ "$android_libcpp_root/libs/$android_app_abi" ]
if (component_mode == "shared_library") {
android_libcpp_library = "c++_shared"
} else {
android_libcpp_library = "c++_static"
}
libs += [ "$android_libcpp_library" ]
if (current_cpu == "mipsel") {
@@ -767,6 +752,12 @@ if (is_win) {
# prevent it.
"/wd4503",
# Warning C4589 says: "Constructor of abstract class ignores
# initializer for virtual base class." Disable this warning because it
# is flaky in VS 2015 RTM. It triggers on compiler generated
# copy-constructors in some cases.
"/wd4589",
# C4611: interaction between 'function' and C++ object destruction is
# non-portable
# This warning is unavoidable when using e.g. setjmp/longjmp. MSDN
@@ -803,40 +794,14 @@ if (is_win) {
# Keep this in sync with the similar block in build/common.gypi
if (is_clang) {
default_warning_flags += [
# TODO(hans): Make this list shorter eventually.
"-Qunused-arguments",
"-Wno-c++11-compat-deprecated-writable-strings",
"-Wno-deprecated-declarations",
"-Wno-empty-body",
"-Wno-enum-conversion",
"-Wno-extra-tokens",
"-Wno-ignored-attributes",
"-Wno-incompatible-pointer-types",
"-Wno-int-to-void-pointer-cast",
"-Wno-invalid-noreturn",
"-Wno-logical-op-parentheses",
"-Wno-microsoft",
"-Wno-missing-braces",
"-Wno-missing-declarations",
"-Wno-msvc-include",
"-Wno-null-dereference",
"-Wno-overloaded-virtual",
"-Wno-parentheses",
"-Wno-pointer-sign",
"-Wno-reorder",
"-Wno-return-type-c-linkage",
"-Wno-self-assign",
"-Wno-sometimes-uninitialized",
"-Wno-switch",
"-Wno-tautological-compare",
"-Wno-unknown-pragmas",
"-Wno-unsequenced",
"-Wno-unused-function",
"-Wno-unused-private-field",
"-Wno-unused-value",
"-Wno-unused-variable",
# TODO(hans): Make this list shorter eventually, http://crbug.com/504657
"-Qunused-arguments", # http://crbug.com/504658
"-Wno-microsoft", # http://crbug.com/505296
"-Wno-switch", # http://crbug.com/505308
"-Wno-unknown-pragmas", # http://crbug.com/505314
"-Wno-unused-function", # http://crbug.com/505316
"-Wno-unused-value", # http://crbug.com/505318
"-Wno-unused-local-typedef", # http://crbug.com/411648
"-Wno-inconsistent-missing-override", #http://crbug.com/428099
]
}
} else {
@@ -943,8 +908,11 @@ if (is_clang) {
if (!is_nacl) {
# Flags NaCl does not recognize.
default_warning_flags += [
# TODO(hans): Get this cleaned up.
# TODO(hans): Get this cleaned up, http://crbug.com/428099
"-Wno-inconsistent-missing-override",
# TODO(thakis): Enable this, crbug.com/507717
"-Wno-shift-negative-value",
]
}
}
@@ -1016,6 +984,18 @@ config("no_chromium_code") {
cflags += [ "-Wno-unused-result" ]
}
if (is_clang) {
cflags += [
# TODO(mgiuca): Move this suppression into individual third-party
# libraries as required. http://crbug.com/505301.
"-Wno-overloaded-virtual",
# Lots of third-party libraries have unused variables. Instead of
# suppressing them individually, we just blanket suppress them here.
"-Wno-unused-variable",
]
}
if (is_linux || is_android) {
cflags += [
# Don't warn about printf format problems. This is off by default in gcc
@@ -1088,12 +1068,11 @@ config("no_size_t_to_int_warning") {
# configs += [ "//build/config/compiler/optimize_max" ]
# Shared settings for both "optimize" and "optimize_max" configs.
# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
if (is_win) {
common_optimize_on_cflags = [
"/O2",
"/Ob2", # both explicit and auto inlining.
"/Oy-", # disable omitting frame pointers, must be after /o2.
"/Os", # favor size over speed.
"/Ob2", # Both explicit and auto inlining.
"/Oy-", # Disable omitting frame pointers, must be after /O2.
]
if (!is_asan) {
common_optimize_on_cflags += [
@@ -1159,15 +1138,16 @@ if (is_win) {
# Default "optimization on" config. On Windows, this favors size over speed.
config("optimize") {
cflags = common_optimize_on_cflags
ldflags = common_optimize_on_ldflags
if (is_win) {
cflags += [ "/Os" ] # favor size over speed.
# Favor size over speed, /O1 must be before the common flags. The GYP
# build also specifies /Os and /GF but these are implied by /O1.
cflags = [ "/O1" ] + common_optimize_on_cflags + [ "/Oi" ]
} else if (is_android || is_ios) {
cflags += [ "-Os" ] # Favor size over speed.
cflags = [ "-Os" ] + common_optimize_on_cflags # Favor size over speed.
} else {
cflags += [ "-O2" ]
cflags = [ "-O2" ] + common_optimize_on_cflags
}
ldflags = common_optimize_on_ldflags
}
# Turn off optimizations.
@@ -1199,11 +1179,11 @@ config("no_optimize") {
# optimization and link-time code generation which is very expensive and should
# be used sparingly.
config("optimize_max") {
cflags = common_optimize_on_cflags
ldflags = common_optimize_on_ldflags
if (is_win) {
cflags -= [ "/Os" ]
cflags += [ "/Ot" ] # Favor speed over size.
# Favor speed over size, /O2 must be before the common flags. The GYP
# build also specifies /Ot, /Oi, and /GF, but these are implied by /O2.
cflags = [ "/O2" ] + common_optimize_on_cflags
if (is_official_build) {
# TODO(GYP): TODO(dpranke): Should these only be on in an official
# build, or on all the time? For now we'll require official build so
@@ -1220,7 +1200,7 @@ config("optimize_max") {
ldflags += [ "/LTCG" ]
}
} else {
cflags += [ "-O2" ]
cflags = [ "-O2" ] + common_optimize_on_cflags
}
}

View File

@@ -12,10 +12,9 @@
# to set up feature flags.
declare_args() {
# Use OpenSSL instead of NSS. This is used for Android, Mac, NaCl untrusted
# code, and Windows, and is experimental in other cases (see
# http://crbug.com/62803).
use_openssl = is_android || is_mac || is_nacl || is_win
# Use OpenSSL instead of NSS. This is used for all platforms but iOS. (See
# http://crbug.com/338886).
use_openssl = !is_ios
}
# True when we're using OpenSSL for representing certificates. When targeting

View File

@@ -125,6 +125,9 @@ use_udev = is_linux
# Enable the spell checker.
enable_spellcheck = !is_android
# Use the operating system's spellchecker rather than hunspell.
use_platform_spellchecker = is_android || is_mac
enable_pepper_cdms = enable_plugins && (is_linux || is_mac || is_win)
# Enable basic printing support and UI.
@@ -165,7 +168,8 @@ win_pdf_metafile_for_printing = true
# Whether we are using the rlz library or not. Platforms like Android send
# rlz codes for searches but do not use the library.
enable_rlz = is_chrome_branded && (is_win || is_mac || is_ios || is_chromeos)
enable_rlz_support = is_win || is_mac || is_ios || is_chromeos
enable_rlz = is_chrome_branded && enable_rlz_support
enable_settings_app = enable_app_list && !is_chromeos
@@ -183,8 +187,6 @@ enable_chromevox_next = false
# Use brlapi from brltty for braille display support.
use_brlapi = is_chromeos
enable_media_router = !is_ios && !is_android
# Option controlling the use of GConf (the classic GNOME configuration
# system).
# TODO(GYP) also require !embedded to enable.
@@ -197,3 +199,6 @@ enable_hangout_services_extension = false
# Whether to back up data before sync.
enable_pre_sync_backup = is_win || is_mac || (is_linux && !is_chromeos)
# WebVR support disabled until platform implementations have been added
enable_webvr = false

View File

@@ -35,25 +35,6 @@ config("sdk") {
}
}
pkg_config("atk") {
packages = [ "atk" ]
atk_lib_dir = exec_script(pkg_config_script,
[
"--libdir",
"atk",
],
"string")
defines = [ "ATK_LIB_DIR=\"$atk_lib_dir\"" ]
}
# gn orders flags on a target before flags from configs. The default config
# adds -Wall, and these flags have to be after -Wall -- so they need to come
# from a config and can't be on the target directly.
config("atk_warnings") {
# glib uses the pre-c++11 typedef-as-static_assert hack.
cflags = [ "-Wno-unused-local-typedef" ]
}
config("fontconfig") {
libs = [ "fontconfig" ]
}

View File

@@ -8,12 +8,9 @@ import("//build/config/sanitizers/sanitizers.gni")
# shared_libraries. Unconditionally depend upon this target as it is empty if
# |is_asan|, |is_lsan|, |is_tsan|, |is_msan| and |use_custom_libcxx| are false.
group("deps") {
# TODO(vtl): Chromium has the following (but we don't have
# instrumented_libraries).
# deps = [
# "//third_party/instrumented_libraries:deps",
# ]
deps = []
deps = [
"//third_party/instrumented_libraries:deps",
]
if (is_asan || is_lsan || is_tsan || is_msan) {
public_configs = [ ":sanitizer_options_link_helper" ]
deps += [ ":options_sources" ]

View File

@@ -6,9 +6,7 @@ declare_args() {
# Use libc++ (buildtools/third_party/libc++ and
# buildtools/third_party/libc++abi) instead of stdlibc++ as standard library.
# This is intended to be used for instrumented builds.
# TODO(vtl): We don't use this, since building fails, for some reason.
use_custom_libcxx = false
# use_custom_libcxx = (is_asan && is_linux) || is_tsan || is_msan
use_custom_libcxx = (is_asan && is_linux) || is_tsan || is_msan
# Track where uninitialized memory originates from. From fastest to slowest:
# 0 - no tracking, 1 - track only the initial allocation site, 2 - track the

View File

@@ -36,10 +36,9 @@ if (current_toolchain == default_toolchain && target_sysroot != "") {
# For official builds, use the sysroot checked into the internal source repo
# so that the builds work on older versions of Linux.
if (current_cpu == "x64") {
sysroot =
rebase_path("//chrome/installer/linux/debian_wheezy_amd64-sysroot")
sysroot = rebase_path("//build/linux/debian_wheezy_amd64-sysroot")
} else if (current_cpu == "x86") {
sysroot = rebase_path("//chrome/installer/linux/debian_wheezy_i386-sysroot")
sysroot = rebase_path("//build/linux/debian_wheezy_i386-sysroot")
} else {
# Any other builds don't use a sysroot.
sysroot = ""

View File

@@ -103,8 +103,8 @@ if (current_cpu == "x64") {
# 5.02 = Windows Server 2003.
subsystem_version_suffix = ",5.02"
} else {
# Don't specify a min version on x86.
subsystem_version_suffix = ""
# 5.01 = Windows XP.
subsystem_version_suffix = ",5.01"
}
config("console") {

View File

@@ -34,7 +34,8 @@ def print_landmines():
builder() == 'ninja'):
print 'Need to clobber winja goma due to backend cwd cache fix.'
if platform() == 'android':
print 'Clobber because of unions.'
print 'Clobber: to handle new way of suppressing findbugs failures.'
print 'Clobber to fix gyp not rename package name (crbug.com/457038)'
if platform() == 'win' and builder() == 'ninja':
print 'Compile on cc_unittests fails due to symbols removed in r185063.'
if platform() == 'linux' and builder() == 'ninja':
@@ -72,7 +73,8 @@ def print_landmines():
print 'Remove NaCl toolchains from the output dir (crbug.com/456902)'
if platform() == 'ios':
print 'Clobber iOS to workaround Xcode deps bug (crbug.com/485435)'
print 'Clobber: https://github.com/domokit/mojo/issues/269'
if platform() == 'win':
print 'Clobber to delete stale generated files (crbug.com/510086)'
def main():

View File

@@ -13,9 +13,12 @@ SDK_EXTRAS_JSON_FILE = os.path.join(os.path.dirname(__file__),
def main():
with open(SDK_EXTRAS_JSON_FILE) as json_file:
packages = json.load(json_file)
for package in packages:
print package['package'].replace('_', ' ')
out = []
for package in packages:
out.append(package['package_id'])
print ','.join(out)
if __name__ == '__main__':
sys.exit(main())

View File

@@ -5,7 +5,6 @@
"""A utility script for downloading versioned Syzygy binaries."""
import cStringIO
import hashlib
import errno
import json
@@ -17,15 +16,15 @@ import shutil
import stat
import sys
import subprocess
import urllib2
import tempfile
import time
import zipfile
_LOGGER = logging.getLogger(os.path.basename(__file__))
# The URL where official builds are archived.
_SYZYGY_ARCHIVE_URL = ('https://syzygy-archive.commondatastorage.googleapis.com'
'/builds/official/%(revision)s')
# The relative path where official builds are archived in their GS bucket.
_SYZYGY_ARCHIVE_PATH = ('/builds/official/%(revision)s')
# A JSON file containing the state of the download directory. If this file and
# directory state do not agree, then the binaries will be downloaded and
@@ -49,17 +48,6 @@ _RESOURCES = [
lambda x: x.filename.endswith('.dll.pdb'))]
def _Shell(*cmd, **kw):
"""Runs |cmd|, returns the results from Popen(cmd).communicate()."""
_LOGGER.debug('Executing %s.', cmd)
prog = subprocess.Popen(cmd, shell=True, **kw)
stdout, stderr = prog.communicate()
if prog.returncode != 0:
raise RuntimeError('Command "%s" returned %d.' % (cmd, prog.returncode))
return (stdout, stderr)
def _LoadState(output_dir):
"""Loads the contents of the state file for a given |output_dir|, returning
None if it doesn't exist.
@@ -248,12 +236,50 @@ def _CleanState(output_dir, state, dry_run=False):
return deleted
def _Download(url):
"""Downloads the given URL and returns the contents as a string."""
response = urllib2.urlopen(url)
if response.code != 200:
raise RuntimeError('Failed to download "%s".' % url)
return response.read()
def _FindGsUtil():
"""Looks for depot_tools and returns the absolute path to gsutil.py."""
for path in os.environ['PATH'].split(os.pathsep):
path = os.path.abspath(path)
git_cl = os.path.join(path, 'git_cl.py')
gs_util = os.path.join(path, 'gsutil.py')
if os.path.exists(git_cl) and os.path.exists(gs_util):
return gs_util
return None
def _GsUtil(*cmd):
"""Runs the given command in gsutil with exponential backoff and retries."""
gs_util = _FindGsUtil()
cmd = [sys.executable, gs_util] + list(cmd)
retries = 3
timeout = 4 # Seconds.
while True:
_LOGGER.debug('Running %s', cmd)
prog = subprocess.Popen(cmd, shell=False)
prog.communicate()
# Stop retrying on success.
if prog.returncode == 0:
return
# Raise a permanent failure if retries have been exhausted.
if retries == 0:
raise RuntimeError('Command "%s" returned %d.' % (cmd, prog.returncode))
_LOGGER.debug('Sleeping %d seconds and trying again.', timeout)
time.sleep(timeout)
retries -= 1
timeout *= 2
def _Download(resource):
"""Downloads the given GS resource to a temporary file, returning its path."""
tmp = tempfile.mkstemp(suffix='syzygy_archive')
os.close(tmp[0])
url = 'gs://syzygy-archive' + resource
_GsUtil('cp', url, tmp[1])
return tmp[1]
def _InstallBinaries(options, deleted={}):
@@ -261,7 +287,7 @@ def _InstallBinaries(options, deleted={}):
already been cleaned, as it will refuse to overwrite existing files."""
contents = {}
state = { 'revision': options.revision, 'contents': contents }
archive_url = _SYZYGY_ARCHIVE_URL % { 'revision': options.revision }
archive_path = _SYZYGY_ARCHIVE_PATH % { 'revision': options.revision }
if options.resources:
resources = [(resource, resource, '', None)
for resource in options.resources]
@@ -278,33 +304,37 @@ def _InstallBinaries(options, deleted={}):
if not options.dry_run:
os.makedirs(fulldir)
# Download the archive.
url = archive_url + '/' + base
_LOGGER.debug('Retrieving %s archive at "%s".', name, url)
data = _Download(url)
# Download and read the archive.
resource = archive_path + '/' + base
_LOGGER.debug('Retrieving %s archive at "%s".', name, resource)
path = _Download(resource)
_LOGGER.debug('Unzipping %s archive.', name)
archive = zipfile.ZipFile(cStringIO.StringIO(data))
for entry in archive.infolist():
if not filt or filt(entry):
fullpath = os.path.normpath(os.path.join(fulldir, entry.filename))
relpath = os.path.relpath(fullpath, options.output_dir)
if os.path.exists(fullpath):
# If in a dry-run take into account the fact that the file *would*
# have been deleted.
if options.dry_run and relpath in deleted:
pass
else:
raise Exception('Path already exists: %s' % fullpath)
with open(path, 'rb') as data:
archive = zipfile.ZipFile(data)
for entry in archive.infolist():
if not filt or filt(entry):
fullpath = os.path.normpath(os.path.join(fulldir, entry.filename))
relpath = os.path.relpath(fullpath, options.output_dir)
if os.path.exists(fullpath):
# If in a dry-run take into account the fact that the file *would*
# have been deleted.
if options.dry_run and relpath in deleted:
pass
else:
raise Exception('Path already exists: %s' % fullpath)
# Extract the file and update the state dictionary.
_LOGGER.debug('Extracting "%s".', fullpath)
if not options.dry_run:
archive.extract(entry.filename, fulldir)
md5 = _Md5(fullpath)
contents[relpath] = md5
if sys.platform == 'cygwin':
os.chmod(fullpath, os.stat(fullpath).st_mode | stat.S_IXUSR)
# Extract the file and update the state dictionary.
_LOGGER.debug('Extracting "%s".', fullpath)
if not options.dry_run:
archive.extract(entry.filename, fulldir)
md5 = _Md5(fullpath)
contents[relpath] = md5
if sys.platform == 'cygwin':
os.chmod(fullpath, os.stat(fullpath).st_mode | stat.S_IXUSR)
_LOGGER.debug('Removing temporary file "%s".', path)
os.remove(path)
return state
@@ -316,6 +346,9 @@ def _ParseCommandLine():
help='If true then will simply list actions that would be performed.')
option_parser.add_option('--force', action='store_true', default=False,
help='Force an installation even if the binaries are up to date.')
option_parser.add_option('--no-cleanup', action='store_true', default=False,
help='Allow installation on non-Windows platforms, and skip the forced '
'cleanup step.')
option_parser.add_option('--output-dir', type='string',
help='The path where the binaries will be replaced. Existing binaries '
'will only be overwritten if not up to date.')
@@ -408,7 +441,10 @@ def main():
# wasn't gated on OS types, and those OSes downloaded and installed binaries.
# This will cleanup orphaned files on those operating systems.
if sys.platform not in ('win32', 'cygwin'):
return _RemoveOrphanedFiles(options)
if options.no_cleanup:
_LOGGER.debug('Skipping usual cleanup for non-Windows platforms.')
else:
return _RemoveOrphanedFiles(options)
# Load the current installation state, and validate it against the
# requested installation.

View File

@@ -12,14 +12,9 @@ echo 'checking for sdk packages install'
cwd=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# Get the SDK extras packages to install from the DEPS file 'sdkextras' hook.
packages="$(python ${cwd}/get_sdk_extras_packages.py)"
for package in "${packages}"; do
pkg_id=$(${cwd}/../third_party/android_tools/sdk/tools/android list sdk | \
grep -i "$package," | \
awk '/^[ ]*[0-9]*- / {gsub("-",""); print $1}')
if [[ -n ${pkg_id} ]]; then
${cwd}/../third_party/android_tools/sdk/tools/android update sdk --no-ui \
--filter ${pkg_id}
fi
done
if [[ -n "${packages}" ]]; then
${cwd}/../third_party/android_tools/sdk/tools/android update sdk --no-ui \
--filter ${packages}
fi
echo "install-android-sdks.sh complete."

View File

@@ -1,64 +0,0 @@
#!/bin/bash -e
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Script to install dependencies for developing Mojo on Mac OS X.
XCODE_APP="/Applications/Xcode.app"
JDK_VERSION="1.7.0"
echo
INSTRUCTIONS=""
if [ ! -d $XCODE_APP ]; then
INSTRUCTIONS="${INSTRUCTIONS}\n** Install the latest version of Xcode from the Mac App Store."
fi
if [ -z $(which java) ] || ! java -version 2>&1 | grep -q ${JDK_VERSION}; then
temp=$(
echo "** Download the Java JDK (Java SE Development Kit) 7:"
echo " http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html"
)
INSTRUCTIONS="${INSTRUCTIONS}\n$temp"
fi
if [ -z $(which gclient) ] && [ ! -d $HOME/depot_tools ]; then
echo "*** Installing depot_tools in $HOME"
echo
cd $HOME
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
temp=$(
echo "** Add this to your .bash_profile or similar:"
echo " export PATH=\"\${HOME}/depot_tools:\${PATH}\""
)
INSTRUCTIONS="${INSTRUCTIONS}\n$temp"
fi
if [ ! -z $(which brew) ]; then
brew install ant
elif [ ! -z $(which port) ]; then
sudo `which port` install apache-ant
else
INSTRUCTIONS="${INSTRUCTIONS}\n** Install homebrew (brew.sh) or macports (macports.org) and re-run this script."
fi
sudo easy_install pip
sudo pip install requests
echo
echo "All done!"
if [ ! -z "$INSTRUCTIONS" ]; then
echo
echo
echo "**** Follow these final instructions to get going."
echo $INSTRUCTIONS
fi

View File

@@ -0,0 +1,430 @@
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import operator
import os
import platform
import re
import subprocess
import sys
SUPPORTED_UBUNTU_VERSIONS = (
{'number': '12.04', 'codename': 'precise'},
{'number': '14.04', 'codename': 'trusty'},
{'number': '14.10', 'codename': 'utopic'},
{'number': '15.04', 'codename': 'vivid'},
)
# Packages needed for chromeos only.
_packages_chromeos_dev = (
'libbluetooth-dev',
'libxkbcommon-dev',
'realpath',
)
# Packages needed for development.
_packages_dev = (
'apache2.2-bin',
'bison',
'cdbs',
'curl',
'devscripts',
'dpkg-dev',
'elfutils',
'fakeroot',
'flex',
'fonts-thai-tlwg',
'g++',
'git-core',
'git-svn',
'gperf',
'language-pack-da',
'language-pack-fr',
'language-pack-he',
'language-pack-zh-hant',
'libapache2-mod-php5',
'libasound2-dev',
'libav-tools',
'libbrlapi-dev',
'libbz2-dev',
'libcairo2-dev',
'libcap-dev',
'libcups2-dev',
'libcurl4-gnutls-dev',
'libdrm-dev',
'libelf-dev',
'libexif-dev',
'libgconf2-dev',
'libglib2.0-dev',
'libglu1-mesa-dev',
'libgnome-keyring-dev',
'libgtk2.0-dev',
'libkrb5-dev',
'libnspr4-dev',
'libnss3-dev',
'libpam0g-dev',
'libpci-dev',
'libpulse-dev',
'libsctp-dev',
'libspeechd-dev',
'libsqlite3-dev',
'libssl-dev',
'libudev-dev',
'libwww-perl',
'libxslt1-dev',
'libxss-dev',
'libxt-dev',
'libxtst-dev',
'openbox',
'patch',
'perl',
'php5-cgi',
'pkg-config',
'python',
'python-cherrypy3',
'python-crypto',
'python-dev',
'python-numpy',
'python-opencv',
'python-openssl',
'python-psutil',
'python-yaml',
'rpm',
'ruby',
'subversion',
'ttf-dejavu-core',
'ttf-indic-fonts',
'ttf-kochi-gothic',
'ttf-kochi-mincho',
'wdiff',
'xfonts-mathml',
'zip',
)
# Run-time libraries required by chromeos only.
_packages_chromeos_lib = (
'libbz2-1.0',
'libpulse0',
)
# Full list of required run-time libraries.
_packages_lib = (
'libasound2',
'libatk1.0-0',
'libc6',
'libcairo2',
'libcap2',
'libcups2',
'libexif12',
'libexpat1',
'libfontconfig1',
'libfreetype6',
'libglib2.0-0',
'libgnome-keyring0',
'libgtk2.0-0',
'libpam0g',
'libpango1.0-0',
'libpci3',
'libpcre3',
'libpixman-1-0',
'libpng12-0',
'libspeechd2',
'libsqlite3-0',
'libstdc++6',
'libx11-6',
'libxau6',
'libxcb1',
'libxcomposite1',
'libxcursor1',
'libxdamage1',
'libxdmcp6',
'libxext6',
'libxfixes3',
'libxi6',
'libxinerama1',
'libxrandr2',
'libxrender1',
'libxtst6',
'zlib1g',
)
# Debugging symbols for all of the run-time libraries.
_packages_dbg = (
'libatk1.0-dbg',
'libc6-dbg',
'libcairo2-dbg',
'libfontconfig1-dbg',
'libglib2.0-0-dbg',
'libgtk2.0-0-dbg',
'libpango1.0-0-dbg',
'libpcre3-dbg',
'libpixman-1-0-dbg',
'libsqlite3-0-dbg',
'libx11-6-dbg',
'libxau6-dbg',
'libxcb1-dbg',
'libxcomposite1-dbg',
'libxcursor1-dbg',
'libxdamage1-dbg',
'libxdmcp6-dbg',
'libxext6-dbg',
'libxfixes3-dbg',
'libxi6-dbg',
'libxinerama1-dbg',
'libxrandr2-dbg',
'libxrender1-dbg',
'libxtst6-dbg',
'zlib1g-dbg',
)
# 32-bit libraries needed e.g. to compile V8 snapshot for Android or armhf.
_packages_lib32 = (
'linux-libc-dev:i386',
)
# arm cross toolchain packages needed to build chrome on armhf.
_packages_arm = (
'g++-arm-linux-gnueabihf',
'libc6-dev-armhf-cross',
'linux-libc-dev-armhf-cross',
)
# Packages to build NaCl, its toolchains, and its ports.
_packages_naclports = (
'ant',
'autoconf',
'bison',
'cmake',
'gawk',
'intltool',
'xsltproc',
'xutils-dev',
)
_packages_nacl = (
'g++-mingw-w64-i686',
'lib32ncurses5-dev',
'lib32z1-dev',
'libasound2:i386',
'libcap2:i386',
'libelf-dev:i386',
'libexif12:i386',
'libfontconfig1:i386',
'libgconf-2-4:i386',
'libglib2.0-0:i386',
'libgpm2:i386',
'libgtk2.0-0:i386',
'libncurses5:i386',
'libnss3:i386',
'libpango1.0-0:i386',
'libssl1.0.0:i386',
'libtinfo-dev',
'libtinfo-dev:i386',
'libtool',
'libxcomposite1:i386',
'libxcursor1:i386',
'libxdamage1:i386',
'libxi6:i386',
'libxrandr2:i386',
'libxss1:i386',
'libxtst6:i386',
'texinfo',
'xvfb',
)
def is_userland_64_bit():
return platform.architecture()[0] == '64bit'
def package_exists(pkg):
return pkg in subprocess.check_output(['apt-cache', 'pkgnames']).splitlines()
def lsb_release_short_codename():
return subprocess.check_output(
['lsb_release', '--codename', '--short']).strip()
def write_error(message):
sys.stderr.write('ERROR: %s\n' % message)
sys.stderr.flush()
def nonfatal_get_output(*popenargs, **kwargs):
process = subprocess.Popen(
stdout=subprocess.PIPE, stderr=subprocess.PIPE, *popenargs, **kwargs)
stdout, stderr = process.communicate()
retcode = process.poll()
return retcode, stdout, stderr
def compute_dynamic_package_lists():
global _packages_arm
global _packages_dbg
global _packages_dev
global _packages_lib
global _packages_lib32
global _packages_nacl
if is_userland_64_bit():
# 64-bit systems need a minimum set of 32-bit compat packages
# for the pre-built NaCl binaries.
_packages_dev += (
'lib32gcc1',
'lib32stdc++6',
'libc6-i386',
)
# When cross building for arm/Android on 64-bit systems the host binaries
# that are part of v8 need to be compiled with -m32 which means
# that basic multilib support is needed.
# gcc-multilib conflicts with the arm cross compiler (at least in trusty)
# but g++-X.Y-multilib gives us the 32-bit support that we need. Find out
# the appropriate value of X and Y by seeing what version the current
# distribution's g++-multilib package depends on.
output = subprocess.check_output(['apt-cache', 'depends', 'g++-multilib'])
multilib_package = re.search(r'g\+\+-[0-9.]+-multilib', output).group()
_packages_lib32 += (multilib_package,)
lsb_codename = lsb_release_short_codename()
# Find the proper version of libstdc++6-4.x-dbg.
if lsb_codename == 'precise':
_packages_dbg += ('libstdc++6-4.6-dbg',)
elif lsb_codename == 'trusty':
_packages_dbg += ('libstdc++6-4.8-dbg',)
else:
_packages_dbg += ('libstdc++6-4.9-dbg',)
# Work around for dependency issue Ubuntu/Trusty: http://crbug.com/435056 .
if lsb_codename == 'trusty':
_packages_arm += (
'g++-4.8-multilib-arm-linux-gnueabihf',
'gcc-4.8-multilib-arm-linux-gnueabihf',
)
# Find the proper version of libgbm-dev. We can't just install libgbm-dev as
# it depends on mesa, and only one version of mesa can exists on the system.
# Hence we must match the same version or this entire script will fail.
mesa_variant = ''
for variant in ('-lts-trusty', '-lts-utopic'):
rc, stdout, stderr = nonfatal_get_output(
['dpkg-query', '-Wf\'{Status}\'', 'libgl1-mesa-glx' + variant])
if 'ok installed' in output:
mesa_variant = variant
_packages_dev += (
'libgbm-dev' + mesa_variant,
'libgl1-mesa-dev' + mesa_variant,
'libgles2-mesa-dev' + mesa_variant,
'mesa-common-dev' + mesa_variant,
)
if package_exists('ttf-mscorefonts-installer'):
_packages_dev += ('ttf-mscorefonts-installer',)
else:
_packages_dev += ('msttcorefonts',)
if package_exists('libnspr4-dbg'):
_packages_dbg += ('libnspr4-dbg', 'libnss3-dbg')
_packages_lib += ('libnspr4', 'libnss3')
else:
_packages_dbg += ('libnspr4-0d-dbg', 'libnss3-1d-dbg')
_packages_lib += ('libnspr4-0d', 'libnss3-1d')
if package_exists('libjpeg-dev'):
_packages_dev += ('libjpeg-dev',)
else:
_packages_dev += ('libjpeg62-dev',)
if package_exists('libudev1'):
_packages_dev += ('libudev1',)
_packages_nacl += ('libudev1:i386',)
else:
_packages_dev += ('libudev0',)
_packages_nacl += ('libudev0:i386',)
if package_exists('libbrlapi0.6'):
_packages_dev += ('libbrlapi0.6',)
else:
_packages_dev += ('libbrlapi0.5',)
# Some packages are only needed if the distribution actually supports
# installing them.
if package_exists('appmenu-gtk'):
_packages_lib += ('appmenu-gtk',)
_packages_dev += _packages_chromeos_dev
_packages_lib += _packages_chromeos_lib
_packages_nacl += _packages_naclports
def quick_check(packages):
rc, stdout, stderr = nonfatal_get_output([
'dpkg-query', '-W', '-f', '${PackageSpec}:${Status}\n'] + list(packages))
if rc == 0 and not stderr:
return 0
print stderr
return 1
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--quick-check', action='store_true',
help='quickly try to determine if dependencies are '
'installed (this avoids interactive prompts and '
'sudo commands so might not be 100% accurate)')
parser.add_argument('--unsupported', action='store_true',
help='attempt installation even on unsupported systems')
args = parser.parse_args(argv)
lsb_codename = lsb_release_short_codename()
if not args.unsupported and not args.quick_check:
if lsb_codename not in map(
operator.itemgetter('codename'), SUPPORTED_UBUNTU_VERSIONS):
supported_ubuntus = ['%(number)s (%(codename)s)' % v
for v in SUPPORTED_UBUNTU_VERSIONS]
write_error('Only Ubuntu %s are currently supported.' %
', '.join(supported_ubuntus))
return 1
if platform.machine() not in ('i686', 'x86_64'):
write_error('Only x86 architectures are currently supported.')
return 1
if os.geteuid() != 0 and not args.quick_check:
print 'Running as non-root user.'
print 'You might have to enter your password one or more times'
print 'for \'sudo\'.'
print
compute_dynamic_package_lists()
packages = (_packages_dev + _packages_lib + _packages_dbg + _packages_lib32 +
_packages_arm + _packages_nacl)
def packages_key(pkg):
s = pkg.rsplit(':', 1)
if len(s) == 1:
return (s, '')
return s
packages = sorted(set(packages), key=packages_key)
if args.quick_check:
return quick_check(packages)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))

View File

@@ -223,7 +223,8 @@ target="${distname}${arch}"
d|D) sudo rm -rf "/var/lib/chroot/${target}" \
"/usr/local/bin/${target%bit}" \
"/etc/schroot/mount-${target}" \
"/etc/schroot/script-${target}"
"/etc/schroot/script-${target}" \
"/etc/schroot/${target}"
sudo sed -ni '/^[[]'"${target%bit}"']$/,${
:1;n;/^[[]/b2;b1;:2;p;n;b2};p' \
"/etc/schroot/schroot.conf"
@@ -349,13 +350,41 @@ grep -qs ubuntu.com /usr/share/debootstrap/scripts/"${distname}" &&
if [ -z "${chroot_groups}" ]; then
chroot_groups="${admin},$(id -gn)"
fi
# Older versions of schroot wanted a "priority=" line, whereas recent
# versions deprecate "priority=" and warn if they see it. We don't have
# a good feature test, but scanning for the string "priority=" in the
# existing "schroot.conf" file is a good indication of what to do.
priority=$(grep -qs 'priority=' /etc/schroot/schroot.conf &&
if [ -d '/etc/schroot/default' ]; then
new_version=1
fstab="/etc/schroot/${target}/fstab"
else
new_version=0
fstab="/etc/schroot/mount-${target}"
fi
if [ "$new_version" = "1" ]; then
sudo cp -ar /etc/schroot/default /etc/schroot/${target}
sudo sh -c 'cat >>/etc/schroot/schroot.conf' <<EOF
[${target%bit}]
description=${brand} ${distname} ${arch}
type=directory
directory=/var/lib/chroot/${target}
users=root
groups=${chroot_groups}
root-groups=${chroot_groups}
personality=linux$([ "${arch}" != 64bit ] && echo 32)
profile=${target}
EOF
[ -n "${bind_mounts}" -a "${bind_mounts}" != "NONE" ] &&
printf "${bind_mounts}" |
sudo sh -c "cat >>${fstab}"
else
# Older versions of schroot wanted a "priority=" line, whereas recent
# versions deprecate "priority=" and warn if they see it. We don't have
# a good feature test, but scanning for the string "priority=" in the
# existing "schroot.conf" file is a good indication of what to do.
priority=$(grep -qs 'priority=' /etc/schroot/schroot.conf &&
echo 'priority=3' || :)
sudo sh -c 'cat >>/etc/schroot/schroot.conf' <<EOF
sudo sh -c 'cat >>/etc/schroot/schroot.conf' <<EOF
[${target%bit}]
description=${brand} ${distname} ${arch}
type=directory
@@ -369,42 +398,43 @@ ${priority}
EOF
# Set up a list of mount points that is specific to this
# chroot environment.
sed '/^FSTAB=/s,"[^"]*","/etc/schroot/mount-'"${target}"'",' \
/etc/schroot/script-defaults |
sudo sh -c 'cat >/etc/schroot/script-'"${target}"
sed '\,^/home[/[:space:]],s/\([,[:space:]]\)bind[[:space:]]/\1rbind /' \
/etc/schroot/mount-defaults |
sudo sh -c 'cat > /etc/schroot/mount-'"${target}"
# Set up a list of mount points that is specific to this
# chroot environment.
sed '/^FSTAB=/s,"[^"]*","'"${fstab}"'",' \
/etc/schroot/script-defaults |
sudo sh -c 'cat >/etc/schroot/script-'"${target}"
sed '\,^/home[/[:space:]],s/\([,[:space:]]\)bind[[:space:]]/\1rbind /' \
/etc/schroot/mount-defaults |
sudo sh -c "cat > ${fstab}"
fi
# Add the extra mount points that the user told us about
[ -n "${bind_mounts}" -a "${bind_mounts}" != "NONE" ] &&
printf "${bind_mounts}" |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${fstab}"
# If this system has a "/media" mountpoint, import it into the chroot
# environment. Most modern distributions use this mount point to
# automatically mount devices such as CDROMs, USB sticks, etc...
if [ -d /media ] &&
! grep -qs '^/media' /etc/schroot/mount-"${target}"; then
! grep -qs '^/media' "${fstab}"; then
echo '/media /media none rw,rbind 0 0' |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${fstab}"
fi
# Share /dev/shm, /run and /run/shm.
grep -qs '^/dev/shm' /etc/schroot/mount-"${target}" ||
grep -qs '^/dev/shm' "${fstab}" ||
echo '/dev/shm /dev/shm none rw,bind 0 0' |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${fstab}"
if [ ! -d "/var/lib/chroot/${target}/run" ] &&
! grep -qs '^/run' /etc/schroot/mount-"${target}"; then
! grep -qs '^/run' "${fstab}"; then
echo '/run /run none rw,bind 0 0' |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${fstab}"
fi
if ! grep -qs '^/run/shm' /etc/schroot/mount-"${target}"; then
if ! grep -qs '^/run/shm' "${fstab}"; then
{ [ -d /run ] && echo '/run/shm /run/shm none rw,bind 0 0' ||
echo '/dev/shm /run/shm none rw,bind 0 0'; } |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${fstab}"
fi
# Set up a special directory that changes contents depending on the target
@@ -412,7 +442,7 @@ fi
d="$(readlink -f "${HOME}/chroot" 2>/dev/null || echo "${HOME}/chroot")"
s="${d}/.${target}"
echo "${s} ${d} none rw,bind 0 0" |
sudo sh -c 'cat >>/etc/schroot/mount-'"${target}"
sudo sh -c 'cat >>'"${target}"
mkdir -p "${s}"
# Install a helper script to launch commands in the chroot
@@ -717,7 +747,7 @@ if [ -x "${script}" ]; then
# installing the Chrome build depencies. This prevents the chroot
# session from being closed. So, we always try to shut down any running
# instance of dbus and rsyslog.
sudo /usr/local/bin/"${target%bit}" sh -c "${script} --no-lib32;
sudo /usr/local/bin/"${target%bit}" sh -c "${script};
rc=$?;
/etc/init.d/cron stop >/dev/null 2>&1 || :;
/etc/init.d/rsyslog stop >/dev/null 2>&1 || :;

View File

@@ -21,6 +21,7 @@ IDR_DEFAULT_FAVICON_64
IDR_DIR_HEADER_HTML
IDR_DISTILLABLE_PAGE_SERIALIZED_MODEL
IDR_DISTILLER_CSS
IDR_DISTILLER_IOS_CSS
IDR_DISTILLER_JS
IDR_DOM_DISTILLER_VIEWER_HTML
IDR_DOM_DISTILLER_VIEWER_JS
@@ -104,7 +105,6 @@ IDR_TRANSLATE_JS
IDR_UBER_UTILS_JS
IDR_WEBUI_CSS_TEXT_DEFAULTS
IDR_WEBUI_I18N_TEMPLATE_JS
IDR_WEBUI_I18N_TEMPLATE_POLYMER_JS
IDR_WEBUI_JSTEMPLATE_JS
IDR_WEBUI_JS_LOAD_TIME_DATA
IDS_ABOUT_MAC
@@ -143,8 +143,6 @@ IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS
IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_AMEX
IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED
IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED_AMEX
IDS_AUTOFILL_CARD_UNMASK_PROMPT_TITLE
IDS_AUTOFILL_CARD_UNMASK_PROMPT_UPDATE_TITLE
IDS_AUTOFILL_CC_AMEX
IDS_AUTOFILL_CC_AMEX_SHORT
IDS_AUTOFILL_CC_DINERS
@@ -326,6 +324,7 @@ IDS_DOM_DISTILLER_JAVASCRIPT_DISABLED_CONTENT
IDS_DOM_DISTILLER_QUALITY_ANSWER_NO
IDS_DOM_DISTILLER_QUALITY_ANSWER_YES
IDS_DOM_DISTILLER_QUALITY_QUESTION
IDS_DOM_DISTILLER_VIEWER_CLOSE_READER_VIEW
IDS_DOM_DISTILLER_VIEWER_FAILED_TO_FIND_ARTICLE_CONTENT
IDS_DOM_DISTILLER_VIEWER_FAILED_TO_FIND_ARTICLE_TITLE
IDS_DOM_DISTILLER_VIEWER_LOADING_STRING
@@ -536,12 +535,12 @@ IDS_FLAGS_DISABLE_WEBGL_NAME
IDS_FLAGS_DISABLE_WEBRTC_DESCRIPTION
IDS_FLAGS_DISABLE_WEBRTC_NAME
IDS_FLAGS_ENABLE
IDS_FLAGS_ENABLE_ACCELERATED_MJPEG_DECODE_DESCRIPTION
IDS_FLAGS_ENABLE_ACCELERATED_MJPEG_DECODE_NAME
IDS_FLAGS_ENABLE_APPS_SHOW_ON_FIRST_PAINT_DESCRIPTION
IDS_FLAGS_ENABLE_APPS_SHOW_ON_FIRST_PAINT_NAME
IDS_FLAGS_ENABLE_CONTEXTUAL_SEARCH
IDS_FLAGS_ENABLE_CONTEXTUAL_SEARCH_DESCRIPTION
IDS_FLAGS_ENABLE_DEFERRED_IMAGE_DECODING_DESCRIPTION
IDS_FLAGS_ENABLE_DEFERRED_IMAGE_DECODING_NAME
IDS_FLAGS_ENABLE_DEVTOOLS_EXPERIMENTS_DESCRIPTION
IDS_FLAGS_ENABLE_DEVTOOLS_EXPERIMENTS_NAME
IDS_FLAGS_ENABLE_DOWNLOAD_RESUMPTION_DESCRIPTION
@@ -820,9 +819,7 @@ IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_NO_CT
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY
IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT
IDS_PAGE_INFO_SITE_INFO_TITLE
IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE
IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE
IDS_PASSWORD_MANAGER_BLACKLIST_BUTTON

View File

@@ -15,14 +15,15 @@ build is clobbered.
import difflib
import errno
import gyp_environment
import logging
import optparse
import os
import shutil
import sys
import subprocess
import time
import clobber
import landmine_utils
@@ -55,79 +56,6 @@ def get_build_dir(build_tool, is_iphone=False):
return os.path.abspath(ret)
def extract_gn_build_commands(build_ninja_file):
"""Extracts from a build.ninja the commands to run GN.
The commands to run GN are the gn rule and build.ninja build step at the
top of the build.ninja file. We want to keep these when deleting GN builds
since we want to preserve the command-line flags to GN.
On error, returns the empty string."""
result = ""
with open(build_ninja_file, 'r') as f:
# Read until the second blank line. The first thing GN writes to the file
# is the "rule gn" and the second is the section for "build build.ninja",
# separated by blank lines.
num_blank_lines = 0
while num_blank_lines < 2:
line = f.readline()
if len(line) == 0:
return '' # Unexpected EOF.
result += line
if line[0] == '\n':
num_blank_lines = num_blank_lines + 1
return result
def delete_build_dir(build_dir):
# GN writes a build.ninja.d file. Note that not all GN builds have args.gn.
build_ninja_d_file = os.path.join(build_dir, 'build.ninja.d')
if not os.path.exists(build_ninja_d_file):
shutil.rmtree(build_dir)
return
# GN builds aren't automatically regenerated when you sync. To avoid
# messing with the GN workflow, erase everything but the args file, and
# write a dummy build.ninja file that will automatically rerun GN the next
# time Ninja is run.
build_ninja_file = os.path.join(build_dir, 'build.ninja')
build_commands = extract_gn_build_commands(build_ninja_file)
try:
gn_args_file = os.path.join(build_dir, 'args.gn')
with open(gn_args_file, 'r') as f:
args_contents = f.read()
except IOError:
args_contents = ''
shutil.rmtree(build_dir)
# Put back the args file (if any).
os.mkdir(build_dir)
if args_contents != '':
with open(gn_args_file, 'w') as f:
f.write(args_contents)
# Write the build.ninja file sufficiently to regenerate itself.
with open(os.path.join(build_dir, 'build.ninja'), 'w') as f:
if build_commands != '':
f.write(build_commands)
else:
# Couldn't parse the build.ninja file, write a default thing.
f.write('''rule gn
command = gn -q gen //out/%s/
description = Regenerating ninja files
build build.ninja: gn
generator = 1
depfile = build.ninja.d
''' % (os.path.split(build_dir)[1]))
# Write a .d file for the build which references a nonexistant file. This
# will make Ninja always mark the build as dirty.
with open(build_ninja_d_file, 'w') as f:
f.write('build.ninja: nonexistant_file.gn\n')
def clobber_if_necessary(new_landmines):
"""Does the work of setting, planting, and triggering landmines."""
out_dir = get_build_dir(landmine_utils.builder())
@@ -149,14 +77,7 @@ def clobber_if_necessary(new_landmines):
sys.stdout.write('Clobbering due to:\n')
sys.stdout.writelines(diff)
# Clobber contents of build directory but not directory itself: some
# checkouts have the build directory mounted.
for f in os.listdir(out_dir):
path = os.path.join(out_dir, f)
if os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
delete_build_dir(path)
clobber.clobber(out_dir)
# Save current set of landmines for next time.
with open(landmines_path, 'w') as f:
@@ -199,6 +120,7 @@ def main():
if landmine_utils.builder() in ('dump_dependency_json', 'eclipse'):
return 0
gyp_environment.SetEnvironment()
landmines = []
for s in landmine_scripts:

View File

@@ -0,0 +1,6 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Override nacl's build directory.
nacl_shared_build_dir = "//build"

View File

@@ -9,5 +9,5 @@ if (is_android) {
# TODO(sky): nuke this. Temporary while sorting out http://crbug.com/465456.
enable_correct_v8_arch = false
v8_use_external_startup_data = false
v8_use_external_startup_data = !(is_chromeos || is_win)
v8_extra_library_files = []

View File

@@ -97,6 +97,9 @@ char kLSanDefaultSuppressions[] =
// http://crbug.com/356306
"leak:content::SetProcessTitleFromCommandLine\n"
// http://crbug.com/506433
"leak:blink::ResourceFetcher::garbageCollectDocumentResources\n"
// PLEASE READ ABOVE BEFORE ADDING NEW SUPPRESSIONS.
// End of suppressions.

View File

@@ -270,9 +270,6 @@ char kTSanDefaultSuppressions[] =
"race:g_next_user_script_id\n"
// http://crbug.com/389098
"race:webrtc::RtpToNtpMs\n"
"race:webrtc::UpdateRtcpList\n"
"race:webrtc::RemoteNtpTimeEstimator::Estimate\n"
"race:webrtc::voe::TransmitMixer::EnableStereoChannelSwapping\n"
// http://crbug.com/397022
@@ -306,6 +303,8 @@ char kTSanDefaultSuppressions[] =
// https://crbug.com/455665
"race:mojo::common::*::tick_clock\n"
"race:mojo::common::internal::NowTicks\n"
"race:tracked_objects::ThreadData::InitializeThreadContext\n"
// https://crbug.com/459429
"race:randomnessPid\n"

View File

@@ -111,6 +111,16 @@ static_library("gtest") {
configs -= [ "//build/config/compiler:chromium_code" ]
configs += [ "//build/config/compiler:no_chromium_code" ]
config("gtest_warnings") {
if (is_win && is_clang) {
# The Mutex constructor initializer list in gtest-port.cc is incorrectly
# ordered. See
# https://groups.google.com/d/msg/googletestframework/S5uSV8L2TX8/U1FaTDa6J6sJ.
cflags = [ "-Wno-reorder" ]
}
}
configs += [ ":gtest_warnings" ]
}
source_set("gtest_main") {

View File

@@ -28,6 +28,23 @@ android_java_prebuilt("uiautomator_java") {
jar_path = "$android_sdk/uiautomator.jar"
}
android_resources("android_support_design_resources") {
v14_skip = true
resource_dirs = [ "$android_sdk_root/extras/android/support/design/res" ]
deps = [
":android_support_v7_appcompat_resources",
]
custom_package = "android.support.design"
}
android_java_prebuilt("android_support_design_java") {
deps = [
":android_support_v7_appcompat_java",
":android_support_design_resources",
]
jar_path = "$android_sdk_root/extras/android/support/design/libs/android-support-design.jar"
}
android_java_prebuilt("android_support_v13_java") {
jar_path =
"$android_sdk_root/extras/android/support/v13/android-support-v13.jar"
@@ -88,7 +105,33 @@ android_resources("google_play_services_default_resources") {
android_java_prebuilt("google_play_services_default_java") {
deps = [
":android_support_v13_java",
":android_support_v7_mediarouter_java",
":google_play_services_default_resources",
]
proguard_preprocess = true
proguard_config = "//third_party/android_tools/proguard.flags"
# TODO(dgn) deps should not complain about having a custom action here
# Currently, there is no guarantee that the data_deps actions will complete before the current one runs
data_deps = [ ":check_sdk_extras_version" ]
jar_path = "$android_sdk_root/extras/google/google_play_services/libproject/google-play-services_lib/libs/google-play-services.jar"
}
action("check_sdk_extras_version") {
script = "//build/check_sdk_extras_version.py"
args = [
"--package-id",
"extra-google-google_play_services",
"--package-location",
rebase_path("$android_sdk_root/extras/google/google_play_services"),
"--stamp",
rebase_path("$target_gen_dir/checked_sdk_extras_version.stamp"),
]
inputs = [
"//build/android_sdk_extras.json",
"$android_sdk_root/extras/google/google_play_services/source.properties",
]
outputs = [
"$target_gen_dir/checked_sdk_extras_version.stamp",
]
}

View File

@@ -1,146 +0,0 @@
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//testing/test.gni")
config("cacheinvalidation_config") {
include_dirs = [
"overrides",
"src",
]
}
static_library("cacheinvalidation") {
sources = [
"overrides/google/cacheinvalidation/deps/callback.h",
"overrides/google/cacheinvalidation/deps/gmock.h",
"overrides/google/cacheinvalidation/deps/googletest.h",
"overrides/google/cacheinvalidation/deps/logging.h",
"overrides/google/cacheinvalidation/deps/mutex.h",
"overrides/google/cacheinvalidation/deps/random.cc",
"overrides/google/cacheinvalidation/deps/random.h",
"overrides/google/cacheinvalidation/deps/scoped_ptr.h",
"overrides/google/cacheinvalidation/deps/sha1-digest-function.h",
"overrides/google/cacheinvalidation/deps/stl-namespace.h",
"overrides/google/cacheinvalidation/deps/string_util.h",
"overrides/google/cacheinvalidation/deps/time.h",
"src/google/cacheinvalidation/deps/digest-function.h",
"src/google/cacheinvalidation/impl/basic-system-resources.cc",
"src/google/cacheinvalidation/impl/basic-system-resources.h",
"src/google/cacheinvalidation/impl/checking-invalidation-listener.cc",
"src/google/cacheinvalidation/impl/checking-invalidation-listener.h",
"src/google/cacheinvalidation/impl/client-protocol-namespace-fix.h",
"src/google/cacheinvalidation/impl/constants.cc",
"src/google/cacheinvalidation/impl/constants.h",
"src/google/cacheinvalidation/impl/digest-store.h",
"src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.cc",
"src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.h",
"src/google/cacheinvalidation/impl/invalidation-client-core.cc",
"src/google/cacheinvalidation/impl/invalidation-client-core.h",
"src/google/cacheinvalidation/impl/invalidation-client-factory.cc",
"src/google/cacheinvalidation/impl/invalidation-client-impl.cc",
"src/google/cacheinvalidation/impl/invalidation-client-impl.h",
"src/google/cacheinvalidation/impl/invalidation-client-util.h",
"src/google/cacheinvalidation/impl/log-macro.h",
"src/google/cacheinvalidation/impl/object-id-digest-utils.cc",
"src/google/cacheinvalidation/impl/object-id-digest-utils.h",
"src/google/cacheinvalidation/impl/persistence-utils.cc",
"src/google/cacheinvalidation/impl/persistence-utils.h",
"src/google/cacheinvalidation/impl/proto-converter.cc",
"src/google/cacheinvalidation/impl/proto-converter.h",
"src/google/cacheinvalidation/impl/proto-helpers.cc",
"src/google/cacheinvalidation/impl/proto-helpers.h",
"src/google/cacheinvalidation/impl/protocol-handler.cc",
"src/google/cacheinvalidation/impl/protocol-handler.h",
"src/google/cacheinvalidation/impl/recurring-task.cc",
"src/google/cacheinvalidation/impl/recurring-task.h",
"src/google/cacheinvalidation/impl/registration-manager.cc",
"src/google/cacheinvalidation/impl/registration-manager.h",
"src/google/cacheinvalidation/impl/repeated-field-namespace-fix.h",
"src/google/cacheinvalidation/impl/run-state.h",
"src/google/cacheinvalidation/impl/safe-storage.cc",
"src/google/cacheinvalidation/impl/safe-storage.h",
"src/google/cacheinvalidation/impl/simple-registration-store.cc",
"src/google/cacheinvalidation/impl/simple-registration-store.h",
"src/google/cacheinvalidation/impl/smearer.h",
"src/google/cacheinvalidation/impl/statistics.cc",
"src/google/cacheinvalidation/impl/statistics.h",
"src/google/cacheinvalidation/impl/throttle.cc",
"src/google/cacheinvalidation/impl/throttle.h",
"src/google/cacheinvalidation/impl/ticl-message-validator.cc",
"src/google/cacheinvalidation/impl/ticl-message-validator.h",
"src/google/cacheinvalidation/include/invalidation-client-factory.h",
"src/google/cacheinvalidation/include/invalidation-client.h",
"src/google/cacheinvalidation/include/invalidation-listener.h",
"src/google/cacheinvalidation/include/system-resources.h",
"src/google/cacheinvalidation/include/types.h",
]
# TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
configs += [ "//build/config/compiler:no_size_t_to_int_warning" ]
public_configs = [ ":cacheinvalidation_config" ]
public_deps = [
"src/google/cacheinvalidation:cacheinvalidation_proto_cpp",
]
deps = [
"//base",
]
}
test("cacheinvalidation_unittests") {
sources = [
"src/google/cacheinvalidation/impl/invalidation-client-impl_test.cc",
"src/google/cacheinvalidation/impl/protocol-handler_test.cc",
"src/google/cacheinvalidation/impl/recurring-task_test.cc",
"src/google/cacheinvalidation/impl/throttle_test.cc",
"src/google/cacheinvalidation/test/deterministic-scheduler.cc",
"src/google/cacheinvalidation/test/deterministic-scheduler.h",
"src/google/cacheinvalidation/test/test-logger.cc",
"src/google/cacheinvalidation/test/test-logger.h",
"src/google/cacheinvalidation/test/test-utils.cc",
"src/google/cacheinvalidation/test/test-utils.h",
]
deps = [
":cacheinvalidation",
"src/google/cacheinvalidation:cacheinvalidation_proto_cpp",
"//base",
"//base/test:run_all_unittests",
"//testing/gmock",
"//testing/gtest",
]
}
# TODO(GYP) Test isolation stuff.
if (is_android) {
import("//build/config/android/rules.gni")
# GYP: //third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_proto_java
proto_java_library("cacheinvalidation_proto_java") {
proto_path = "src/proto"
sources = [
"$proto_path/android_channel.proto",
"$proto_path/android_listener.proto",
"$proto_path/android_service.proto",
"$proto_path/channel_common.proto",
"$proto_path/client.proto",
"$proto_path/client_protocol.proto",
"$proto_path/java_client.proto",
"$proto_path/types.proto",
]
}
# GYP: //third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_javalib
android_library("cacheinvalidation_javalib") {
deps = [
":cacheinvalidation_proto_java",
"//third_party/android_protobuf:protobuf_nano_javalib",
"//third_party/android_tools:android_gcm_java",
]
DEPRECATED_java_in_dir = "src/java"
}
}

View File

@@ -1,27 +0,0 @@
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//third_party/protobuf/proto_library.gni")
proto_library("cacheinvalidation_proto_cpp") {
# Depend on cacheinvalidation instead.
visibility = [ "//third_party/cacheinvalidation/*" ]
sources = [
"client.proto",
"client_gateway.proto",
"client_protocol.proto",
"client_test_internal.proto",
"types.proto",
]
if (!is_android) {
sources += [
"android_channel.proto",
"channel_common.proto",
]
}
proto_out_dir = "google/cacheinvalidation"
}

View File

@@ -11,11 +11,10 @@
# Path to .grd file.
#
# outputs (required)
# List of outputs from grit, relative to the target_gen_dir. If supplied,
# a call to Grit to compute the outputs can be skipped which will make
# GN run faster. Grit will verify at build time that this list is correct
# and will fail if there is a mismatch between the outputs specified by
# the .grd file and the outputs list here.
# List of outputs from grit, relative to the target_gen_dir. Grit will
# verify at build time that this list is correct and will fail if there
# is a mismatch between the outputs specified by the .grd file and the
# outputs list here.
#
# To get this list, you can look in the .grd file for
# <output filename="..." and put those filename here. The base directory
@@ -50,6 +49,10 @@
# output_dir, but if multiple targets with the same name end up in
# the same output_dir, they can collide.
#
# depfile_dir (optional)
# If set, used to store the depfile and corresponding stamp file.
# Defaults to output_dir
#
# use_qualified_include (optional)
# If set, output_dir is not added to include_dirs.
#
@@ -331,6 +334,12 @@ template("grit") {
grit_output_name = target_name
}
if (defined(invoker.depfile_dir)) {
depfile_dir = invoker.depfile_dir
} else {
depfile_dir = output_dir
}
# These are all passed as arguments to the script so have to be relative to
# the build directory.
if (resource_ids != "") {
@@ -383,7 +392,7 @@ template("grit") {
script = "//tools/grit/grit.py"
inputs = grit_inputs
depfile = "$output_dir/${grit_output_name}_stamp.d"
depfile = "$depfile_dir/${grit_output_name}_stamp.d"
outputs = [ "${depfile}.stamp" ] + grit_outputs
args = [

View File

@@ -64,20 +64,18 @@ template("android_gcc_toolchain") {
android_strip = "${tool_prefix}strip"
mkdir_command = "mkdir -p lib.stripped"
strip_command =
"$android_strip --strip-unneeded -o $temp_stripped_soname $soname"
replace_command = "if ! cmp -s $temp_stripped_soname $stripped_soname; then mv $temp_stripped_soname $stripped_soname; fi"
postsolink = "$mkdir_command && $strip_command && $replace_command"
postsolink = "$strip_command && $replace_command"
solink_outputs = [ stripped_soname ]
default_output_extension = android_product_extension
# We make the assumption that the gcc_toolchain will produce an exe with
# the following definition.
exe = "{{root_out_dir}}/{{target_output_name}}{{output_extension}}"
stripped_exe = "exe.stripped/$exe"
mkdir_command = "mkdir -p exe.stripped"
strip_command = "$android_strip --strip-unneeded -o $stripped_exe $exe"
postlink = "$mkdir_command && $strip_command"
postlink = "$android_strip --strip-unneeded -o $stripped_exe $exe"
link_outputs = [ stripped_exe ]
}
}

View File

@@ -95,7 +95,7 @@ template("gcc_toolchain") {
depsformat = "gcc"
description = "CC {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -105,7 +105,7 @@ template("gcc_toolchain") {
depsformat = "gcc"
description = "CXX {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -116,7 +116,7 @@ template("gcc_toolchain") {
depsformat = "gcc"
description = "ASM {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -160,6 +160,9 @@ template("gcc_toolchain") {
# overrides it (in which case {{output_extension}} will be what the target
# specifies).
default_output_extension = ".so"
if (defined(invoker.default_output_extension)) {
default_output_extension = invoker.default_output_extension
}
output_prefix = "lib"

View File

@@ -54,7 +54,7 @@ template("mac_toolchain") {
depsformat = "gcc"
description = "CC {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -64,7 +64,7 @@ template("mac_toolchain") {
depsformat = "gcc"
description = "CXX {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -75,7 +75,7 @@ template("mac_toolchain") {
depsformat = "gcc"
description = "ASM {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -85,7 +85,7 @@ template("mac_toolchain") {
depsformat = "gcc"
description = "OBJC {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}
@@ -95,7 +95,7 @@ template("mac_toolchain") {
depsformat = "gcc"
description = "OBJCXX {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.o",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.o",
]
}

View File

@@ -80,12 +80,15 @@ template("msvc_toolchain") {
tool("cc") {
rspfile = "{{output}}.rsp"
# TODO(brettw) enable this when GN support in the binary has been rolled.
#precompiled_header_type = "msvc"
pdbname = "{{target_out_dir}}/{{target_output_name}}_c.pdb"
command = "ninja -t msvc -e $env -- $cl /nologo /showIncludes /FC @$rspfile /c {{source}} /Fo{{output}} /Fd$pdbname"
depsformat = "msvc"
description = "CC {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.obj",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.obj",
]
rspfile_content = "{{defines}} {{include_dirs}} {{cflags}} {{cflags_c}}"
}
@@ -93,13 +96,16 @@ template("msvc_toolchain") {
tool("cxx") {
rspfile = "{{output}}.rsp"
# TODO(brettw) enable this when GN support in the binary has been rolled.
#precompiled_header_type = "msvc"
# The PDB name needs to be different between C and C++ compiled files.
pdbname = "{{target_out_dir}}/{{target_output_name}}_cc.pdb"
command = "ninja -t msvc -e $env -- $cl /nologo /showIncludes /FC @$rspfile /c {{source}} /Fo{{output}} /Fd$pdbname"
depsformat = "msvc"
description = "CXX {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.obj",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.obj",
]
rspfile_content = "{{defines}} {{include_dirs}} {{cflags}} {{cflags_cc}}"
}
@@ -107,7 +113,7 @@ template("msvc_toolchain") {
tool("rc") {
command = "$python_path gyp-win-tool rc-wrapper $env rc.exe {{defines}} {{include_dirs}} /fo{{output}} {{source}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.res",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.res",
]
description = "RC {{output}}"
}
@@ -118,7 +124,7 @@ template("msvc_toolchain") {
command = "$python_path gyp-win-tool asm-wrapper $env ml.exe {{defines}} {{include_dirs}} /safeseh /c /Fo {{output}} {{source}}"
description = "ASM {{output}}"
outputs = [
"{{source_out_dir}}/{{target_output_name}}.{{source_name_part}}.obj",
"{{target_out_dir}}/{{target_output_name}}/{{source_name_part}}.obj",
]
}

View File

@@ -101,5 +101,13 @@ template("midl") {
public_deps = [
":$action_name",
]
config("midl_warnings") {
if (is_clang) {
# MIDL generates code like "#endif !_MIDL_USE_GUIDDEF_"
cflags = [ "-Wno-extra-tokens" ]
}
}
configs += [ ":midl_warnings" ]
}
}

View File

@@ -26,3 +26,23 @@ action("webkit_version") {
rebase_path(output_file, root_build_dir),
]
}
action("chrome_version_json") {
script = "version.py"
_chrome_version_path = "//chrome/VERSION"
inputs = [
_chrome_version_path,
]
_output_file = "$root_gen_dir/CHROME_VERSION.json"
outputs = [
_output_file,
]
args = [
"--file",
rebase_path(_chrome_version_path, root_build_dir),
"--template",
"{\"full-quoted\": \"\\\"@MAJOR@.@MINOR@.@BUILD@.@PATCH@\\\"\"}",
"--output",
rebase_path(_output_file, root_build_dir),
]
}

View File

@@ -121,7 +121,7 @@ def FetchGitRevision(directory):
return VersionInfo('git', '%s-%s' % (hsh, pos))
def FetchGitSVNURLAndRevision(directory, svn_url_regex):
def FetchGitSVNURLAndRevision(directory, svn_url_regex, go_deeper):
"""
Fetch the Subversion URL and revision through Git.
@@ -130,7 +130,10 @@ def FetchGitSVNURLAndRevision(directory, svn_url_regex):
Returns:
A tuple containing the Subversion URL and revision.
"""
proc = RunGitCommand(directory, ['log', '-1', '--format=%b'])
git_args = ['log', '-1', '--format=%b']
if go_deeper:
git_args.append('--grep=git-svn-id')
proc = RunGitCommand(directory, git_args)
if proc:
output = proc.communicate()[0].strip()
if proc.returncode == 0 and output:
@@ -149,20 +152,21 @@ def FetchGitSVNURLAndRevision(directory, svn_url_regex):
return None, None
def FetchGitSVNRevision(directory, svn_url_regex):
def FetchGitSVNRevision(directory, svn_url_regex, go_deeper):
"""
Fetch the Git-SVN identifier for the local tree.
Errors are swallowed.
"""
url, revision = FetchGitSVNURLAndRevision(directory, svn_url_regex)
url, revision = FetchGitSVNURLAndRevision(directory, svn_url_regex, go_deeper)
if url and revision:
return VersionInfo(url, revision)
return None
def FetchVersionInfo(default_lastchange, directory=None,
directory_regex_prior_to_src_url='chrome|blink|svn'):
directory_regex_prior_to_src_url='chrome|blink|svn',
go_deeper=False):
"""
Returns the last change (in the form of a branch, revision tuple),
from some appropriate revision control system.
@@ -171,7 +175,7 @@ def FetchVersionInfo(default_lastchange, directory=None,
r'.*/(' + directory_regex_prior_to_src_url + r')(/.*)')
version_info = (FetchSVNRevision(directory, svn_url_regex) or
FetchGitSVNRevision(directory, svn_url_regex) or
FetchGitSVNRevision(directory, svn_url_regex, go_deeper) or
FetchGitRevision(directory))
if not version_info:
if default_lastchange and os.path.exists(default_lastchange):
@@ -256,6 +260,9 @@ def main(argv=None):
"file-output-related options.")
parser.add_option("-s", "--source-dir", metavar="DIR",
help="Use repository in the given directory.")
parser.add_option("--git-svn-go-deeper", action='store_true',
help="In a Git-SVN repo, dig down to the last committed " +
"SVN change (historic behaviour).")
opts, args = parser.parse_args(argv[1:])
out_file = opts.output
@@ -274,7 +281,9 @@ def main(argv=None):
else:
src_dir = os.path.dirname(os.path.abspath(__file__))
version_info = FetchVersionInfo(opts.default_lastchange, src_dir)
version_info = FetchVersionInfo(opts.default_lastchange,
directory=src_dir,
go_deeper=opts.git_svn_go_deeper)
if version_info.revision == None:
version_info.revision = '0'

View File

@@ -129,7 +129,9 @@ def FilterTestNames(all_tests, gtest_filter):
Filtered subset of the given list of test names.
"""
pattern_groups = gtest_filter.split('-')
positive_patterns = pattern_groups[0].split(':')
positive_patterns = ['*']
if pattern_groups[0]:
positive_patterns = pattern_groups[0].split(':')
negative_patterns = None
if len(pattern_groups) > 1:
negative_patterns = pattern_groups[1].split(':')

View File

@@ -0,0 +1,56 @@
commit 2f12ff08cc9215273040893a9b6c2b3fabccfb6b
Author: Adam Barth <abarth@chromium.org>
Date: Thu Jul 16 18:00:01 2015 -0700
Improve dependencies
diff --git a/sky/build/sky_app.gni b/sky/build/sky_app.gni
index 950bf82..6890cf6 100644
--- a/sky/build/sky_app.gni
+++ b/sky/build/sky_app.gni
@@ -28,7 +28,7 @@ template("sky_app") {
bundle_prefix = target_name
- copy("copy_${bundle_prefix}_bundle") {
+ copy("gen_${bundle_prefix}_bundle") {
sources = [
"$target_gen_dir/app.skyx",
]
@@ -50,16 +50,20 @@ template("sky_app") {
"$target_gen_dir/app.skyx",
]
deps = [
- "//third_party/icu",
- ":copy_${bundle_prefix}_bundle",
+ ":$skyx_target_name",
+ ":gen_${bundle_prefix}_bundle",
+ "//third_party/icu:icudata",
]
if (defined(invoker.bundles)) {
foreach(bundle, invoker.bundles) {
bundle_gen_dir = get_label_info(bundle, "target_gen_dir")
+ bundle_dir = get_label_info(bundle, "dir")
bundle_name = get_label_info(bundle, "name")
sources += [ "$bundle_gen_dir/${bundle_name}.skyx" ]
- deps += [ bundle ]
+ deps += [
+ "$bundle_dir:gen_${bundle_name}_bundle",
+ ]
}
}
}
diff --git a/sky/shell/BUILD.gn b/sky/shell/BUILD.gn
index 88c9d68..ae169d3 100644
--- a/sky/shell/BUILD.gn
+++ b/sky/shell/BUILD.gn
@@ -136,7 +136,7 @@ if (is_android) {
"$root_build_dir/icudtl.dat",
]
deps = [
- "//third_party/icu",
+ "//third_party/icu:icudata",
]
}
} else if (is_ios) {

View File

@@ -20,6 +20,7 @@ public class RobotiumBundleGenerator implements ResultsBundleGenerator {
public Bundle generate(Map<String, ResultsBundleGenerator.TestResult> rawResults) {
int testsPassed = 0;
int testsFailed = 0;
int testsErrored = 0;
for (Map.Entry<String, ResultsBundleGenerator.TestResult> entry : rawResults.entrySet()) {
switch (entry.getValue()) {
@@ -32,6 +33,9 @@ public class RobotiumBundleGenerator implements ResultsBundleGenerator {
Log.d(TAG, "FAILED: " + entry.getKey());
++testsFailed;
break;
case UNKNOWN:
++testsErrored;
break;
default:
Log.w(TAG, "Unhandled: " + entry.getKey() + ", "
+ entry.getValue().toString());
@@ -40,10 +44,11 @@ public class RobotiumBundleGenerator implements ResultsBundleGenerator {
}
StringBuilder resultBuilder = new StringBuilder();
if (testsFailed > 0) {
resultBuilder.append(
"\nFAILURES!!! Tests run: " + Integer.toString(rawResults.size())
+ ", Failures: " + Integer.toString(testsFailed) + ", Errors: 0");
if (testsFailed > 0 || testsErrored > 0) {
resultBuilder.append("\nFAILURES!!! ")
.append("Tests run: ").append(Integer.toString(rawResults.size()))
.append(", Failures: ").append(Integer.toString(testsFailed))
.append(", Errors: ").append(Integer.toString(testsErrored));
} else {
resultBuilder.append("\nOK (" + Integer.toString(testsPassed) + " tests)");
}

View File

@@ -55,6 +55,7 @@
'type': 'none',
'dependencies': [
'appurify_support.gyp:appurify_support_java',
'on_device_instrumentation.gyp:reporter_java',
'../../base/base.gyp:base_native_libraries_gen',
'../../base/base.gyp:base_java',
],

View File

@@ -6,11 +6,17 @@ package org.chromium.native_test;
import android.os.Bundle;
import org.chromium.base.Log;
import java.io.File;
/**
* An {@link android.app.Activity} for running native browser tests.
*/
public abstract class NativeBrowserTestActivity extends NativeTestActivity {
private static final String TAG = "cr.native_test";
private static final String BROWSER_TESTS_FLAGS[] = {
// content::kSingleProcessTestsFlag
"--single_process",
@@ -32,15 +38,48 @@ public abstract class NativeBrowserTestActivity extends NativeTestActivity {
@Override
public void onStart() {
deletePrivateDataDirectory();
initializeBrowserProcess();
super.onStart();
}
/** Deletes a file or directory along with any of its children.
*
* Note that, like File.delete(), this returns false if the file or directory couldn't be
* fully deleted. This means that, in the directory case, some files may be deleted even if
* the entire directory couldn't be.
*
* @param file The file or directory to delete.
* @return Whether or not the file or directory was deleted.
*/
private static boolean deleteRecursive(File file) {
if (file == null) return true;
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
if (!deleteRecursive(child)) {
return false;
}
}
}
return file.delete();
}
private void deletePrivateDataDirectory() {
File privateDataDirectory = getPrivateDataDirectory();
if (!deleteRecursive(privateDataDirectory)) {
Log.e(TAG, "Failed to remove %s", privateDataDirectory.getAbsolutePath());
}
}
/** Returns the test suite's private data directory. */
protected abstract File getPrivateDataDirectory();
/** Initializes the browser process.
*
* This generally includes loading native libraries and switching to the native command line,
* among other things.
*/
protected abstract void initializeBrowserProcess();
}

View File

@@ -10,12 +10,16 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import org.chromium.base.CommandLine;
import org.chromium.base.JNINamespace;
import org.chromium.base.Log;
import org.chromium.test.reporter.TestStatusReporter;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Android's NativeActivity is mostly useful for pure-native code.
@@ -28,16 +32,17 @@ public class NativeTestActivity extends Activity {
"org.chromium.native_test.NativeTestActivity.CommandLineFile";
public static final String EXTRA_COMMAND_LINE_FLAGS =
"org.chromium.native_test.NativeTestActivity.CommandLineFlags";
public static final String EXTRA_SHARD =
"org.chromium.native_test.NativeTestActivity.Shard";
public static final String EXTRA_STDOUT_FILE =
"org.chromium.native_test.NativeTestActivity.StdoutFile";
private static final String TAG = "cr.native_test";
private static final String EXTRA_RUN_IN_SUB_THREAD = "RunInSubThread";
// We post a delayed task to run tests so that we do not block onCreate().
private static final long RUN_TESTS_DELAY_IN_MS = 300;
private String mCommandLineFilePath;
private StringBuilder mCommandLineFlags = new StringBuilder();
private TestStatusReporter mReporter;
private boolean mRunInSubThread = false;
private boolean mStdoutFifo = false;
private String mStdoutFilePath;
@@ -48,6 +53,7 @@ public class NativeTestActivity extends Activity {
CommandLine.init(new String[]{});
parseArgumentsFromIntent(getIntent());
mReporter = new TestStatusReporter(this);
}
private void parseArgumentsFromIntent(Intent intent) {
@@ -68,6 +74,19 @@ public class NativeTestActivity extends Activity {
mRunInSubThread = intent.hasExtra(EXTRA_RUN_IN_SUB_THREAD);
ArrayList<String> shard = intent.getStringArrayListExtra(EXTRA_SHARD);
if (shard != null) {
StringBuilder filterFlag = new StringBuilder();
filterFlag.append("--gtest_filter=");
for (Iterator<String> test_iter = shard.iterator(); test_iter.hasNext();) {
filterFlag.append(test_iter.next());
if (test_iter.hasNext()) {
filterFlag.append(":");
}
}
appendCommandLineFlags(filterFlag.toString());
}
mStdoutFilePath = intent.getStringExtra(EXTRA_STDOUT_FILE);
if (mStdoutFilePath == null) {
mStdoutFilePath = new File(getFilesDir(), "test.fifo").getAbsolutePath();
@@ -94,19 +113,21 @@ public class NativeTestActivity extends Activity {
} else {
// Post a task to run the tests. This allows us to not block
// onCreate and still run tests on the main thread.
new Handler().postDelayed(new Runnable() {
new Handler().post(new Runnable() {
@Override
public void run() {
runTests();
}
}, RUN_TESTS_DELAY_IN_MS);
});
}
}
private void runTests() {
mReporter.testRunStarted(Process.myPid());
nativeRunTests(mCommandLineFlags.toString(), mCommandLineFilePath, mStdoutFilePath,
mStdoutFifo, getApplicationContext());
finish();
mReporter.testRunFinished(Process.myPid());
}
// Signal a failure of the native test loader to python scripts

View File

@@ -5,13 +5,19 @@
package org.chromium.native_test;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import android.util.SparseArray;
import org.chromium.base.Log;
import org.chromium.test.reporter.TestStatusReceiver;
import org.chromium.test.support.ResultsBundleGenerator;
import org.chromium.test.support.RobotiumBundleGenerator;
@@ -20,10 +26,15 @@ import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -33,22 +44,38 @@ import java.util.regex.Pattern;
public class NativeTestInstrumentationTestRunner extends Instrumentation {
public static final String EXTRA_NATIVE_TEST_ACTIVITY =
"org.chromium.native_test.NativeTestInstrumentationTestRunner."
+ "NativeTestActivity";
"org.chromium.native_test.NativeTestInstrumentationTestRunner.NativeTestActivity";
public static final String EXTRA_SHARD_NANO_TIMEOUT =
"org.chromium.native_test.NativeTestInstrumentationTestRunner.ShardNanoTimeout";
public static final String EXTRA_SHARD_SIZE_LIMIT =
"org.chromium.native_test.NativeTestInstrumentationTestRunner.ShardSizeLimit";
public static final String EXTRA_TEST_LIST_FILE =
"org.chromium.native_test.NativeTestInstrumentationTestRunner.TestList";
private static final String TAG = "cr.native_test";
private static final int ACCEPT_TIMEOUT_MS = 5000;
private static final long DEFAULT_SHARD_NANO_TIMEOUT = 60 * 1000000000L;
// Default to no size limit.
private static final int DEFAULT_SHARD_SIZE_LIMIT = 0;
private static final String DEFAULT_NATIVE_TEST_ACTIVITY =
"org.chromium.native_test.NativeUnitTestActivity";
private static final Pattern RE_TEST_OUTPUT = Pattern.compile("\\[ *([^ ]*) *\\] ?([^ ]+) .*");
private static final Pattern RE_TEST_OUTPUT =
Pattern.compile("\\[ *([^ ]*) *\\] ?([^ ]+)( .*)?$");
private ResultsBundleGenerator mBundleGenerator = new RobotiumBundleGenerator();
private String mCommandLineFile;
private String mCommandLineFlags;
private Handler mHandler = new Handler();
private String mNativeTestActivity;
private Bundle mLogBundle = new Bundle();
private TestStatusReceiver mReceiver;
private Map<String, ResultsBundleGenerator.TestResult> mResults =
new HashMap<String, ResultsBundleGenerator.TestResult>();
private Queue<ArrayList<String>> mShards = new ArrayDeque<ArrayList<String>>();
private long mShardNanoTimeout = DEFAULT_SHARD_NANO_TIMEOUT;
private int mShardSizeLimit = DEFAULT_SHARD_SIZE_LIMIT;
private File mStdoutFile;
private SparseArray<ShardMonitor> mMonitors = new SparseArray<ShardMonitor>();
@Override
public void onCreate(Bundle arguments) {
@@ -57,6 +84,39 @@ public class NativeTestInstrumentationTestRunner extends Instrumentation {
mNativeTestActivity = arguments.getString(EXTRA_NATIVE_TEST_ACTIVITY);
if (mNativeTestActivity == null) mNativeTestActivity = DEFAULT_NATIVE_TEST_ACTIVITY;
String shardNanoTimeout = arguments.getString(EXTRA_SHARD_NANO_TIMEOUT);
if (shardNanoTimeout != null) mShardNanoTimeout = Long.parseLong(shardNanoTimeout);
String shardSizeLimit = arguments.getString(EXTRA_SHARD_SIZE_LIMIT);
if (shardSizeLimit != null) mShardSizeLimit = Integer.parseInt(shardSizeLimit);
String testListFilePath = arguments.getString(EXTRA_TEST_LIST_FILE);
if (testListFilePath != null) {
File testListFile = new File(testListFilePath);
try {
BufferedReader testListFileReader =
new BufferedReader(new FileReader(testListFile));
String test;
ArrayList<String> workingShard = new ArrayList<String>();
while ((test = testListFileReader.readLine()) != null) {
workingShard.add(test);
if (workingShard.size() == mShardSizeLimit) {
mShards.add(workingShard);
workingShard = new ArrayList<String>();
}
}
if (!workingShard.isEmpty()) {
mShards.add(workingShard);
}
testListFileReader.close();
} catch (IOException e) {
Log.e(TAG, "Error reading %s", testListFile.getAbsolutePath(), e);
}
}
try {
mStdoutFile = File.createTempFile(
".temp_stdout_", ".txt", Environment.getExternalStorageDirectory());
@@ -66,62 +126,153 @@ public class NativeTestInstrumentationTestRunner extends Instrumentation {
finish(Activity.RESULT_CANCELED, new Bundle());
return;
}
start();
}
@Override
public void onStart() {
super.onStart();
Bundle results = runTests();
finish(Activity.RESULT_OK, results);
mReceiver = new TestStatusReceiver();
mReceiver.register(getContext());
mReceiver.registerCallback(new TestStatusReceiver.TestRunCallback() {
@Override
public void testRunStarted(int pid) {
if (pid != Process.myPid()) {
ShardMonitor m = new ShardMonitor(
pid, System.nanoTime() + mShardNanoTimeout);
mMonitors.put(pid, m);
mHandler.post(m);
}
}
@Override
public void testRunFinished(int pid) {
ShardMonitor m = mMonitors.get(pid);
if (m != null) {
m.stopped();
mMonitors.remove(pid);
}
mHandler.post(new ShardEnder(pid));
}
});
mHandler.post(new ShardStarter());
}
/** Runs the tests in the NativeTestActivity and returns a Bundle containing the results.
*/
private Bundle runTests() {
Log.i(TAG, "Creating activity.");
Activity activityUnderTest = startNativeTestActivity();
/** Monitors a test shard's execution. */
private class ShardMonitor implements Runnable {
private static final int MONITOR_FREQUENCY_MS = 1000;
Log.i(TAG, "Waiting for tests to finish.");
try {
while (!activityUnderTest.isFinishing()) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted while waiting for activity to be destroyed: ", e);
private long mExpirationNanoTime;
private int mPid;
private AtomicBoolean mStopped;
public ShardMonitor(int pid, long expirationNanoTime) {
mPid = pid;
mExpirationNanoTime = expirationNanoTime;
mStopped = new AtomicBoolean(false);
}
Log.i(TAG, "Getting results.");
Map<String, ResultsBundleGenerator.TestResult> results = parseResults(activityUnderTest);
public void stopped() {
mStopped.set(true);
}
Log.i(TAG, "Parsing results and generating output.");
return mBundleGenerator.generate(results);
@Override
public void run() {
if (mStopped.get()) {
return;
}
if (isAppProcessAlive(getContext(), mPid)) {
if (System.nanoTime() > mExpirationNanoTime) {
Log.e(TAG, "Test process %d timed out.", mPid);
mHandler.post(new ShardEnder(mPid));
return;
} else {
mHandler.postDelayed(this, MONITOR_FREQUENCY_MS);
return;
}
}
Log.e(TAG, "Test process %d died unexpectedly.", mPid);
mHandler.post(new ShardEnder(mPid));
}
}
private static boolean isAppProcessAlive(Context context, int pid) {
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo :
activityManager.getRunningAppProcesses()) {
if (processInfo.pid == pid) return true;
}
return false;
}
/** Starts the NativeTestActivty.
*/
private Activity startNativeTestActivity() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setComponent(new ComponentName(getContext().getPackageName(), mNativeTestActivity));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (mCommandLineFile != null) {
Log.i(TAG, "Passing command line file extra: %s", mCommandLineFile);
i.putExtra(NativeTestActivity.EXTRA_COMMAND_LINE_FILE, mCommandLineFile);
private class ShardStarter implements Runnable {
@Override
public void run() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setComponent(new ComponentName(getContext().getPackageName(), mNativeTestActivity));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (mCommandLineFile != null) {
Log.i(TAG, "Passing command line file extra: %s", mCommandLineFile);
i.putExtra(NativeTestActivity.EXTRA_COMMAND_LINE_FILE, mCommandLineFile);
}
if (mCommandLineFlags != null) {
Log.i(TAG, "Passing command line flag extra: %s", mCommandLineFlags);
i.putExtra(NativeTestActivity.EXTRA_COMMAND_LINE_FLAGS, mCommandLineFlags);
}
if (mShards != null && !mShards.isEmpty()) {
ArrayList<String> shard = mShards.remove();
i.putStringArrayListExtra(NativeTestActivity.EXTRA_SHARD, shard);
}
i.putExtra(NativeTestActivity.EXTRA_STDOUT_FILE, mStdoutFile.getAbsolutePath());
getContext().startActivity(i);
}
if (mCommandLineFlags != null) {
Log.i(TAG, "Passing command line flag extra: %s", mCommandLineFlags);
i.putExtra(NativeTestActivity.EXTRA_COMMAND_LINE_FLAGS, mCommandLineFlags);
}
private class ShardEnder implements Runnable {
private static final int WAIT_FOR_DEATH_MILLIS = 10;
private int mPid;
public ShardEnder(int pid) {
mPid = pid;
}
@Override
public void run() {
if (mPid != Process.myPid()) {
Process.killProcess(mPid);
try {
while (isAppProcessAlive(getContext(), mPid)) {
Thread.sleep(WAIT_FOR_DEATH_MILLIS);
}
} catch (InterruptedException e) {
Log.e(TAG, "%d may still be alive.", mPid, e);
}
}
mResults.putAll(parseResults());
if (mShards != null && !mShards.isEmpty()) {
mHandler.post(new ShardStarter());
} else {
finish(Activity.RESULT_OK, mBundleGenerator.generate(mResults));
}
}
i.putExtra(NativeTestActivity.EXTRA_STDOUT_FILE, mStdoutFile.getAbsolutePath());
return startActivitySync(i);
}
/**
* Generates a map between test names and test results from the instrumented Activity's
* output.
*/
private Map<String, ResultsBundleGenerator.TestResult> parseResults(
Activity activityUnderTest) {
private Map<String, ResultsBundleGenerator.TestResult> parseResults() {
Map<String, ResultsBundleGenerator.TestResult> results =
new HashMap<String, ResultsBundleGenerator.TestResult>();
@@ -153,7 +304,7 @@ public class NativeTestInstrumentationTestRunner extends Instrumentation {
Log.i(TAG, l);
}
} catch (FileNotFoundException e) {
Log.e(TAG, "Couldn't find stdout file file: ", e);
Log.e(TAG, "Couldn't find stdout file: ", e);
} catch (IOException e) {
Log.e(TAG, "Error handling stdout file: ", e);
} finally {

View File

@@ -9,7 +9,6 @@ import android.os.Bundle;
import org.chromium.base.Log;
import org.chromium.base.PathUtils;
import org.chromium.base.PowerMonitor;
import org.chromium.base.ResourceExtractor;
import org.chromium.base.library_loader.NativeLibraries;
/**
@@ -27,11 +26,6 @@ public class NativeUnitTestActivity extends NativeTestActivity {
// Needed by path_utils_unittest.cc
PathUtils.setPrivateDataDirectorySuffix("chrome", getApplicationContext());
ResourceExtractor resourceExtractor = ResourceExtractor.get(getApplicationContext());
resourceExtractor.setExtractAllPaksAndV8SnapshotForTesting();
resourceExtractor.startExtractingResources();
resourceExtractor.waitForCompletion();
// Needed by system_monitor_unittest.cc
PowerMonitor.createForTests(this);

View File

@@ -8,7 +8,8 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import org.chromium.base.Log;
import java.util.ArrayList;
import java.util.List;
@@ -18,12 +19,13 @@ import java.util.List;
*/
public class TestStatusReceiver extends BroadcastReceiver {
private static final String TAG = "ResultReceiver";
private static final String TAG = "cr.test.reporter";
private final List<FailCallback> mFailCallbacks = new ArrayList<FailCallback>();
private final List<HeartbeatCallback> mHeartbeatCallbacks = new ArrayList<HeartbeatCallback>();
private final List<PassCallback> mPassCallbacks = new ArrayList<PassCallback>();
private final List<StartCallback> mStartCallbacks = new ArrayList<StartCallback>();
private final List<TestRunCallback> mTestRunCallbacks = new ArrayList<TestRunCallback>();
/** An IntentFilter that matches the intents that this class can receive. */
private static final IntentFilter INTENT_FILTER;
@@ -33,6 +35,8 @@ public class TestStatusReceiver extends BroadcastReceiver {
filter.addAction(TestStatusReporter.ACTION_TEST_FAILED);
filter.addAction(TestStatusReporter.ACTION_TEST_PASSED);
filter.addAction(TestStatusReporter.ACTION_TEST_STARTED);
filter.addAction(TestStatusReporter.ACTION_TEST_RUN_STARTED);
filter.addAction(TestStatusReporter.ACTION_TEST_RUN_FINISHED);
try {
filter.addDataType(TestStatusReporter.DATA_TYPE_HEARTBEAT);
filter.addDataType(TestStatusReporter.DATA_TYPE_RESULT);
@@ -62,6 +66,12 @@ public class TestStatusReceiver extends BroadcastReceiver {
void testStarted(String testClass, String testMethod);
}
/** A callback used when a test run has started or finished. */
public interface TestRunCallback {
void testRunStarted(int pid);
void testRunFinished(int pid);
}
/** Register a callback for when a test has failed. */
public void registerCallback(FailCallback c) {
mFailCallbacks.add(c);
@@ -82,6 +92,11 @@ public class TestStatusReceiver extends BroadcastReceiver {
mStartCallbacks.add(c);
}
/** Register a callback for when a test run has started or finished. */
public void registerCallback(TestRunCallback c) {
mTestRunCallbacks.add(c);
}
/** Register this receiver using the provided context. */
public void register(Context c) {
c.registerReceiver(this, INTENT_FILTER);
@@ -94,6 +109,7 @@ public class TestStatusReceiver extends BroadcastReceiver {
*/
@Override
public void onReceive(Context context, Intent intent) {
int pid = intent.getIntExtra(TestStatusReporter.EXTRA_PID, 0);
String testClass = intent.getStringExtra(TestStatusReporter.EXTRA_TEST_CLASS);
String testMethod = intent.getStringExtra(TestStatusReporter.EXTRA_TEST_METHOD);
@@ -118,8 +134,18 @@ public class TestStatusReceiver extends BroadcastReceiver {
c.heartbeat();
}
break;
case TestStatusReporter.ACTION_TEST_RUN_STARTED:
for (TestRunCallback c: mTestRunCallbacks) {
c.testRunStarted(pid);
}
break;
case TestStatusReporter.ACTION_TEST_RUN_FINISHED:
for (TestRunCallback c: mTestRunCallbacks) {
c.testRunFinished(pid);
}
break;
default:
Log.e(TAG, "Unrecognized intent received: " + intent.toString());
Log.e(TAG, "Unrecognized intent received: %s", intent.toString());
break;
}
}

View File

@@ -24,8 +24,14 @@ public class TestStatusReporter {
"org.chromium.test.reporter.TestStatusReporter.TEST_PASSED";
public static final String ACTION_TEST_FAILED =
"org.chromium.test.reporter.TestStatusReporter.TEST_FAILED";
public static final String ACTION_TEST_RUN_STARTED =
"org.chromium.test.reporter.TestStatusReporter.TEST_RUN_STARTED";
public static final String ACTION_TEST_RUN_FINISHED =
"org.chromium.test.reporter.TestStatusReporter.TEST_RUN_FINISHED";
public static final String DATA_TYPE_HEARTBEAT = "org.chromium.test.reporter/heartbeat";
public static final String DATA_TYPE_RESULT = "org.chromium.test.reporter/result";
public static final String EXTRA_PID =
"org.chromium.test.reporter.TestStatusReporter.PID";
public static final String EXTRA_TEST_CLASS =
"org.chromium.test.reporter.TestStatusReporter.TEST_CLASS";
public static final String EXTRA_TEST_METHOD =
@@ -57,22 +63,18 @@ public class TestStatusReporter {
}
public void testStarted(String testClass, String testMethod) {
sendBroadcast(testClass, testMethod, ACTION_TEST_STARTED);
sendTestBroadcast(ACTION_TEST_STARTED, testClass, testMethod);
}
public void testPassed(String testClass, String testMethod) {
sendBroadcast(testClass, testMethod, ACTION_TEST_PASSED);
sendTestBroadcast(ACTION_TEST_PASSED, testClass, testMethod);
}
public void testFailed(String testClass, String testMethod) {
sendBroadcast(testClass, testMethod, ACTION_TEST_FAILED);
sendTestBroadcast(ACTION_TEST_FAILED, testClass, testMethod);
}
public void stopHeartbeat() {
mKeepBeating.set(false);
}
private void sendBroadcast(String testClass, String testMethod, String action) {
private void sendTestBroadcast(String action, String testClass, String testMethod) {
Intent i = new Intent(action);
i.setType(DATA_TYPE_RESULT);
i.putExtra(EXTRA_TEST_CLASS, testClass);
@@ -80,4 +82,23 @@ public class TestStatusReporter {
mContext.sendBroadcast(i);
}
public void testRunStarted(int pid) {
sendTestRunBroadcast(ACTION_TEST_RUN_STARTED, pid);
}
public void testRunFinished(int pid) {
sendTestRunBroadcast(ACTION_TEST_RUN_FINISHED, pid);
}
private void sendTestRunBroadcast(String action, int pid) {
Intent i = new Intent(action);
i.setType(DATA_TYPE_RESULT);
i.putExtra(EXTRA_PID, pid);
mContext.sendBroadcast(i);
}
public void stopHeartbeat() {
mKeepBeating.set(false);
}
}

Some files were not shown because too many files have changed in this diff Show More