Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1550)

Side by Side Diff: components/cronet/tools/api_static_checks.py

Issue 2440613003: [Cronet] Enforce implementation does not call through API classes (Closed)
Patch Set: address comments, get test running Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #!/usr/bin/python
2 # Copyright 2016 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 """api_static_checks.py - Check Cronet implementation does not call through
7 API classes.
8 """
9
10 import argparse
11 import os
12 import re
13 import shutil
14 import sys
15 import tempfile
16
17 REPOSITORY_ROOT = os.path.abspath(os.path.join(
18 os.path.dirname(__file__), '..', '..', '..'))
19
20 sys.path.append(os.path.join(REPOSITORY_ROOT, 'build/android/gyp/util'))
21 import build_utils
22
23 # These regular expressions catch the beginning of lines that declare classes
24 # and methods. The first group returned by a match is the class or method name.
25 CLASS_RE = re.compile(r'.*class ([^ ]*) .*\{')
26 METHOD_RE = re.compile(r'.* ([^ ]*)\(.*\);')
27
28 # Allowed exceptions. Adding anything to this list is dangerous and should be
29 # avoided if possible. For now these exceptions are for APIs that existed in
30 # the first version of Cronet and will be supported forever.
31 # TODO(pauljensen): Remove these.
32 ALLOWED_EXCEPTIONS = [
kapishnikov 2016/12/02 20:05:03 I think we should add the callee method signatures
pauljensen 2016/12/16 18:45:57 Done.
33 'org.chromium.net.impl.CronetEngineBuilderImpl/build ->'
34 ' org/chromium/net/ExperimentalCronetEngine/getVersionString',
35 'org.chromium.net.urlconnection.CronetFixedModeOutputStream$UploadDataProviderI'
36 'mpl/read -> org/chromium/net/UploadDataSink/onReadSucceeded',
37 'org.chromium.net.urlconnection.CronetFixedModeOutputStream$UploadDataProviderI'
38 'mpl/rewind -> org/chromium/net/UploadDataSink/onRewindError',
39 'org.chromium.net.urlconnection.CronetHttpURLConnection/disconnect ->'
40 ' org/chromium/net/UrlRequest/cancel',
41 'org.chromium.net.urlconnection.CronetHttpURLConnection/disconnect ->'
42 ' org/chromium/net/UrlResponseInfo/getHttpStatusText',
43 'org.chromium.net.urlconnection.CronetHttpURLConnection/disconnect ->'
44 ' org/chromium/net/UrlResponseInfo/getHttpStatusCode',
45 'org.chromium.net.urlconnection.CronetHttpURLConnection/getHeaderField ->'
46 ' org/chromium/net/UrlResponseInfo/getHttpStatusCode',
47 'org.chromium.net.urlconnection.CronetHttpURLConnection/getErrorStream ->'
48 ' org/chromium/net/UrlResponseInfo/getHttpStatusCode',
49 'org.chromium.net.urlconnection.CronetHttpURLConnection/setConnectTimeout ->'
50 ' org/chromium/net/UrlRequest/read',
51 'org.chromium.net.urlconnection.CronetHttpURLConnection$CronetUrlRequestCallbac'
52 'k/onRedirectReceived -> org/chromium/net/UrlRequest/followRedirect',
53 'org.chromium.net.urlconnection.CronetHttpURLConnection$CronetUrlRequestCallbac'
54 'k/onRedirectReceived -> org/chromium/net/UrlRequest/cancel',
55 'org.chromium.net.urlconnection.CronetChunkedOutputStream$UploadDataProviderImp'
56 'l/read -> org/chromium/net/UploadDataSink/onReadSucceeded',
57 'org.chromium.net.urlconnection.CronetChunkedOutputStream$UploadDataProviderImp'
58 'l/rewind -> org/chromium/net/UploadDataSink/onRewindError',
59 'org.chromium.net.urlconnection.CronetBufferedOutputStream$UploadDataProviderIm'
60 'pl/read -> org/chromium/net/UploadDataSink/onReadSucceeded',
61 'org.chromium.net.urlconnection.CronetBufferedOutputStream$UploadDataProviderIm'
62 'pl/rewind -> org/chromium/net/UploadDataSink/onRewindSucceeded',
63 ]
64
65
66 def find_api_calls(dump, api_classes, bad_calls):
67 # Given a dump of an implementation class, find calls through API classes.
68 # |dump| is the output of "javap -c" on the implementation class files.
69 # |api_classes| is the list of classes comprising the API.
70 # |bad_calls| is the list of calls through API classes. This list is built up
71 # by this function.
72
73 for line in dump:
74 if CLASS_RE.match(line):
75 caller_class = CLASS_RE.match(line).group(1)
76 if METHOD_RE.match(line):
77 caller_method = METHOD_RE.match(line).group(1)
78 if line[8:16] == ': invoke':
79 callee = line.split(' // ')[1].split('Method ')[1].split(':')[0]
kapishnikov 2016/12/02 20:05:03 Can we merge two '//' & 'Method' splits into one s
pauljensen 2016/12/16 18:45:57 No, when calling through an interface it's "Interf
kapishnikov 2016/12/28 21:54:41 Acknowledged.
80 callee_class = callee.split('.')[0]
81 assert callee_class
82 if callee_class in api_classes:
83 callee_method = callee.split('.')[1]
84 assert callee_method
85 # Ignore constructor calls for now as every implementation class
86 # that extends an API class will call them.
87 # TODO(pauljensen): Look into enforcing restricting constructor calls.
kapishnikov 2016/12/02 20:05:03 Let's file a bug for that. I think it is important
pauljensen 2016/12/16 18:45:57 Done, and updated comment.
88 if callee_method == '"<init>"':
89 continue
90 # Ignore VersionSafe calls
91 if 'VersionSafeCallbacks' in caller_class:
92 continue
93 bad_call = '%s/%s -> %s/%s' % (caller_class, caller_method,
94 callee_class, callee_method)
95 if bad_call in ALLOWED_EXCEPTIONS:
96 continue
97 bad_calls += [bad_call]
98
99
100 def main(args):
101 # Returns True if no calls through API classes in implementation.
102
103 parser = argparse.ArgumentParser(
104 description='Check modules do not contain ARM Neon instructions.')
105 parser.add_argument('--api_jar',
106 help='Path to API jar (i.e. cronet_api.jar)',
107 required=True,
108 metavar='path/to/cronet_api.jar')
109 parser.add_argument('--impl_jar',
110 help='Path to implementation jar '
111 '(i.e. cronet_impl_native_java.jar)',
112 required=True,
113 metavar='path/to/cronet_impl_native_java.jar',
114 action='append')
115 parser.add_argument('--stamp', help='Path to touch on success.')
116 opts = parser.parse_args(args)
117
118 temp_dir = tempfile.mkdtemp()
119
120 # Extract API class files from jar
121 jar_cmd = ['jar', 'xf', os.path.abspath(opts.api_jar)]
122 build_utils.CheckOutput(jar_cmd, cwd=temp_dir)
123 shutil.rmtree(os.path.join(temp_dir, 'META-INF'))
124
125 # Collect names of API classes
126 api_classes = []
127 for dirpath, _, filenames in os.walk(temp_dir):
128 if not filenames:
129 continue
130 package = dirpath[len(temp_dir + '/'):]
131 if package:
132 package += '/'
133 for filename in filenames:
134 if filename.endswith('.class'):
135 classname = filename[:-len('.class')]
136 api_classes += [package + classname]
137
138 shutil.rmtree(temp_dir)
139 temp_dir = tempfile.mkdtemp()
140
141 # Extract impl class files from jars
142 for impl_jar in opts.impl_jar:
143 jar_cmd = ['jar', 'xf', os.path.abspath(impl_jar)]
144 build_utils.CheckOutput(jar_cmd, cwd=temp_dir)
145 shutil.rmtree(os.path.join(temp_dir, 'META-INF'))
146
147 # Process classes
148 bad_api_calls = []
149 for dirpath, _, filenames in os.walk(temp_dir):
150 if not filenames:
151 continue
152 # Dump classes
153 dump_file = os.path.join(temp_dir, 'dump.txt')
154 if os.system('javap -c %s > %s' % (
155 ' '.join(os.path.join(dirpath, f) for f in filenames).replace(
156 '$', '\\$'),
157 dump_file)):
158 print 'ERROR: javap failed on ' + ' '.join(filenames)
159 return False
160 # Process class dump
161 with open(dump_file, 'r') as dump:
162 find_api_calls(dump, api_classes, bad_api_calls)
163
164 shutil.rmtree(temp_dir)
165
166 if bad_api_calls:
167 print 'ERROR: Found the following calls from implementation classes through'
168 print ' API classes. These could fail if older API is used that'
169 print ' does not contain newer methods. Please call through a'
170 print ' wrapper class from VersionSafeCallbacks.'
171 print '\n'.join(bad_api_calls)
172
173 if not bad_api_calls and opts.stamp:
174 build_utils.Touch(opts.stamp)
175 return not bad_api_calls
176
177
178 if __name__ == '__main__':
179 sys.exit(0 if main(sys.argv[1:]) else -1)
OLDNEW
« no previous file with comments | « components/cronet/tools/__init__.py ('k') | components/cronet/tools/api_static_checks_unittest.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698