1# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# pylint: disable=R0201
6
7import glob
8import logging
9import os.path
10import subprocess
11import sys
12
13from devil.android import device_errors
14from devil.android.valgrind_tools import base_tool
15from pylib.constants import DIR_SOURCE_ROOT
16
17
18def SetChromeTimeoutScale(device, scale):
19  """Sets the timeout scale in /data/local/tmp/chrome_timeout_scale to scale."""
20  path = '/data/local/tmp/chrome_timeout_scale'
21  if not scale or scale == 1.0:
22    # Delete if scale is None/0.0/1.0 since the default timeout scale is 1.0
23    device.RemovePath(path, force=True, as_root=True)
24  else:
25    device.WriteFile(path, '%f' % scale, as_root=True)
26
27
28
29class AddressSanitizerTool(base_tool.BaseTool):
30  """AddressSanitizer tool."""
31
32  WRAPPER_NAME = '/system/bin/asanwrapper'
33  # Disable memcmp overlap check.There are blobs (gl drivers)
34  # on some android devices that use memcmp on overlapping regions,
35  # nothing we can do about that.
36  EXTRA_OPTIONS = 'strict_memcmp=0,use_sigaltstack=1'
37
38  def __init__(self, device):
39    super(AddressSanitizerTool, self).__init__()
40    self._device = device
41
42  @classmethod
43  def CopyFiles(cls, device):
44    """Copies ASan tools to the device."""
45    libs = glob.glob(os.path.join(DIR_SOURCE_ROOT,
46                                  'third_party/llvm-build/Release+Asserts/',
47                                  'lib/clang/*/lib/linux/',
48                                  'libclang_rt.asan-arm-android.so'))
49    assert len(libs) == 1
50    subprocess.call(
51        [os.path.join(
52             DIR_SOURCE_ROOT,
53             'tools/android/asan/third_party/asan_device_setup.sh'),
54         '--device', str(device),
55         '--lib', libs[0],
56         '--extra-options', AddressSanitizerTool.EXTRA_OPTIONS])
57    device.WaitUntilFullyBooted()
58
59  def GetTestWrapper(self):
60    return AddressSanitizerTool.WRAPPER_NAME
61
62  def GetUtilWrapper(self):
63    """Returns the wrapper for utilities, such as forwarder.
64
65    AddressSanitizer wrapper must be added to all instrumented binaries,
66    including forwarder and the like. This can be removed if such binaries
67    were built without instrumentation. """
68    return self.GetTestWrapper()
69
70  def SetupEnvironment(self):
71    try:
72      self._device.EnableRoot()
73    except device_errors.CommandFailedError as e:
74      # Try to set the timeout scale anyway.
75      # TODO(jbudorick) Handle this exception appropriately after interface
76      #                 conversions are finished.
77      logging.error(str(e))
78    SetChromeTimeoutScale(self._device, self.GetTimeoutScale())
79
80  def CleanUpEnvironment(self):
81    SetChromeTimeoutScale(self._device, None)
82
83  def GetTimeoutScale(self):
84    # Very slow startup.
85    return 20.0
86
87
88TOOL_REGISTRY = {
89    'asan': AddressSanitizerTool,
90}
91
92
93def CreateTool(tool_name, device):
94  """Creates a tool with the specified tool name.
95
96  Args:
97    tool_name: Name of the tool to create.
98    device: A DeviceUtils instance.
99  Returns:
100    A tool for the specified tool_name.
101  """
102  if not tool_name:
103    return base_tool.BaseTool()
104
105  ctor = TOOL_REGISTRY.get(tool_name)
106  if ctor:
107    return ctor(device)
108  else:
109    print 'Unknown tool %s, available tools: %s' % (
110        tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
111    sys.exit(1)
112
113def PushFilesForTool(tool_name, device):
114  """Pushes the files required for |tool_name| to |device|.
115
116  Args:
117    tool_name: Name of the tool to create.
118    device: A DeviceUtils instance.
119  """
120  if not tool_name:
121    return
122
123  clazz = TOOL_REGISTRY.get(tool_name)
124  if clazz:
125    clazz.CopyFiles(device)
126  else:
127    print 'Unknown tool %s, available tools: %s' % (
128        tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
129    sys.exit(1)
130
131