blob: 6c10978f1716a9bce0646ab8ec40711db183a3a9 [file] [log] [blame]
Alex Deymo2bba3812014-08-13 08:49:09 -07001# Copyright 2014 The Chromium OS 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"""Script to remove unused gconv charset modules from a build."""
6
Mike Frysinger383367e2014-09-16 15:06:17 -04007from __future__ import print_function
8
Alex Deymo2bba3812014-08-13 08:49:09 -07009import ahocorasick
10import glob
Alex Deymoda9dd402014-08-13 08:54:18 -070011import lddtree
Alex Deymo2bba3812014-08-13 08:49:09 -070012import operator
13import os
14import stat
15
16from chromite.lib import commandline
17from chromite.lib import cros_build_lib
Ralph Nathan5a582ff2015-03-20 18:18:30 -070018from chromite.lib import cros_logging as logging
Alex Deymo2bba3812014-08-13 08:49:09 -070019from chromite.lib import osutils
20
21
22# Path pattern to search for the gconv-modules file.
23GCONV_MODULES_PATH = 'usr/*/gconv/gconv-modules'
24
25# Sticky modules. These charsets modules are always included even if they
26# aren't used. You can specify any charset name as supported by 'iconv_open',
27# for example, 'LATIN1' or 'ISO-8859-1'.
28STICKY_MODULES = ('UTF-16', 'UTF-32', 'UNICODE')
29
30# List of function names (symbols) known to use a charset as a parameter.
31GCONV_SYMBOLS = (
32 # glibc
33 'iconv_open',
34 'iconv',
35 # glib
36 'g_convert',
37 'g_convert_with_fallback',
38 'g_iconv',
39 'g_locale_to_utf8',
40 'g_get_charset',
41)
42
43
44class GconvModules(object):
45 """Class to manipulate the gconv/gconv-modules file and referenced modules.
46
47 This class parses the contents of the gconv-modules file installed by glibc
48 which provides the definition of the charsets supported by iconv_open(3). It
49 allows to load the current gconv-modules file and rewrite it to include only
50 a subset of the supported modules, removing the other modules.
51
52 Each charset is involved on some transformation between that charset and an
53 internal representation. This transformation is defined on a .so file loaded
54 dynamically with dlopen(3) when the charset defined in this file is requested
55 to iconv_open(3).
56
57 See the comments on gconv-modules file for syntax details.
58 """
59
Mike Frysinger22f6c5a2014-08-18 00:45:54 -040060 def __init__(self, gconv_modules_file):
Alex Deymo2bba3812014-08-13 08:49:09 -070061 """Initialize the class.
62
63 Args:
Mike Frysinger22f6c5a2014-08-18 00:45:54 -040064 gconv_modules_file: Path to gconv/gconv-modules file.
Alex Deymo2bba3812014-08-13 08:49:09 -070065 """
Mike Frysinger22f6c5a2014-08-18 00:45:54 -040066 self._filename = gconv_modules_file
Alex Deymo2bba3812014-08-13 08:49:09 -070067
68 # An alias map of charsets. The key (fromcharset) is the alias name and
69 # the value (tocharset) is the real charset name. We also support a value
70 # that is an alias for another charset.
71 self._alias = {}
72
73 # The modules dict goes from charset to module names (the filenames without
74 # the .so extension). Since several transformations involving the same
75 # charset could be defined in different files, the values of this dict are
76 # a set of module names.
77 self._modules = {}
78
79 def Load(self):
80 """Load the charsets from gconv-modules."""
81 for line in open(self._filename):
82 line = line.split('#', 1)[0].strip()
83 if not line: # Comment
84 continue
85
86 lst = line.split()
87 if lst[0] == 'module':
88 _, fromset, toset, filename = lst[:4]
89 for charset in (fromset, toset):
90 charset = charset.rstrip('/')
91 mods = self._modules.get(charset, set())
92 mods.add(filename)
93 self._modules[charset] = mods
94 elif lst[0] == 'alias':
95 _, fromset, toset = lst
96 fromset = fromset.rstrip('/')
97 toset = toset.rstrip('/')
98 # Warn if the same charset is defined as two different aliases.
99 if self._alias.get(fromset, toset) != toset:
Ralph Nathan59900422015-03-24 10:41:17 -0700100 logging.error('charset "%s" already defined as "%s".', fromset,
101 self._alias[fromset])
Alex Deymo2bba3812014-08-13 08:49:09 -0700102 self._alias[fromset] = toset
103 else:
104 cros_build_lib.Die('Unknown line: %s', line)
105
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700106 logging.debug('Found %d modules and %d alias in %s', len(self._modules),
107 len(self._alias), self._filename)
Alex Deymo2bba3812014-08-13 08:49:09 -0700108 charsets = sorted(self._alias.keys() + self._modules.keys())
109 # Remove the 'INTERNAL' charset from the list, since it is not a charset
110 # but an internal representation used to convert to and from other charsets.
111 if 'INTERNAL' in charsets:
112 charsets.remove('INTERNAL')
113 return charsets
114
115 def Rewrite(self, used_charsets, dry_run=False):
116 """Rewrite gconv-modules file with only the used charsets.
117
118 Args:
119 used_charsets: A list of used charsets. This should be a subset of the
120 list returned by Load().
121 dry_run: Whether this function should not change any file.
122 """
123
124 # Compute the used modules.
125 used_modules = set()
126 for charset in used_charsets:
127 while charset in self._alias:
128 charset = self._alias[charset]
129 used_modules.update(self._modules[charset])
130 unused_modules = reduce(set.union, self._modules.values()) - used_modules
131
Alex Deymo2bba3812014-08-13 08:49:09 -0700132 modules_dir = os.path.dirname(self._filename)
Alex Deymoda9dd402014-08-13 08:54:18 -0700133
134 all_modules = set.union(used_modules, unused_modules)
135 # The list of charsets that depend on a given library. For example,
136 # libdeps['libCNS.so'] is the set of all the modules that require that
137 # library. These libraries live in the same directory as the modules.
138 libdeps = {}
139 for module in all_modules:
140 deps = lddtree.ParseELF(os.path.join(modules_dir, '%s.so' % module),
141 modules_dir, [])
142 if not 'needed' in deps:
143 continue
144 for lib in deps['needed']:
145 # Ignore the libs without a path defined (outside the modules_dir).
146 if deps['libs'][lib]['path']:
147 libdeps[lib] = libdeps.get(lib, set()).union([module])
148
149 used_libdeps = set(lib for lib, deps in libdeps.iteritems()
150 if deps.intersection(used_modules))
151 unused_libdeps = set(libdeps).difference(used_libdeps)
152
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700153 logging.debug('Used modules: %s', ', '.join(sorted(used_modules)))
154 logging.debug('Used dependency libs: %s, '.join(sorted(used_libdeps)))
Alex Deymoda9dd402014-08-13 08:54:18 -0700155
Alex Deymo2bba3812014-08-13 08:49:09 -0700156 unused_size = 0
157 for module in sorted(unused_modules):
158 module_path = os.path.join(modules_dir, '%s.so' % module)
159 unused_size += os.lstat(module_path).st_size
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700160 logging.debug('rm %s', module_path)
Alex Deymo2bba3812014-08-13 08:49:09 -0700161 if not dry_run:
162 os.unlink(module_path)
Alex Deymoda9dd402014-08-13 08:54:18 -0700163
164 unused_libdeps_size = 0
165 for lib in sorted(unused_libdeps):
166 lib_path = os.path.join(modules_dir, lib)
167 unused_libdeps_size += os.lstat(lib_path).st_size
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700168 logging.debug('rm %s', lib_path)
Alex Deymoda9dd402014-08-13 08:54:18 -0700169 if not dry_run:
170 os.unlink(lib_path)
171
Ralph Nathan03047282015-03-23 11:09:32 -0700172 logging.info('Done. Using %d gconv modules. Removed %d unused modules'
173 ' (%.1f KiB) and %d unused dependencies (%.1f KiB)',
174 len(used_modules), len(unused_modules), unused_size / 1024.,
175 len(unused_libdeps), unused_libdeps_size / 1024.)
Alex Deymo2bba3812014-08-13 08:49:09 -0700176
177 # Recompute the gconv-modules file with only the included gconv modules.
178 result = []
179 for line in open(self._filename):
180 lst = line.split('#', 1)[0].strip().split()
181
182 if not lst:
183 result.append(line) # Keep comments and copyright headers.
184 elif lst[0] == 'module':
185 _, _, _, filename = lst[:4]
186 if filename in used_modules:
187 result.append(line) # Used module
188 elif lst[0] == 'alias':
189 _, charset, _ = lst
190 charset = charset.rstrip('/')
191 while charset in self._alias:
192 charset = self._alias[charset]
193 if used_modules.intersection(self._modules[charset]):
194 result.append(line) # Alias to an used module
195 else:
196 cros_build_lib.Die('Unknown line: %s', line)
197
198 if not dry_run:
199 osutils.WriteFile(self._filename, ''.join(result))
200
201
202def MultipleStringMatch(patterns, corpus):
203 """Search a list of strings in a corpus string.
204
205 Args:
206 patterns: A list of strings.
207 corpus: The text where to search for the strings.
208
Mike Frysingerc6a67da2016-09-21 00:47:20 -0400209 Returns:
Alex Deymo2bba3812014-08-13 08:49:09 -0700210 A list of Booleans stating whether each pattern string was found in the
211 corpus or not.
212 """
213 tree = ahocorasick.KeywordTree()
214 for word in patterns:
215 tree.add(word)
216 tree.make()
217
218 result = [False] * len(patterns)
219 for i, j in tree.findall(corpus):
220 match = corpus[i:j]
221 result[patterns.index(match)] = True
222
223 return result
224
225
226def GconvStrip(opts):
227 """Process gconv-modules and remove unused modules.
228
229 Args:
230 opts: The command-line args passed to the script.
231
232 Returns:
233 The exit code number indicating whether the process succeeded.
234 """
235 root_st = os.lstat(opts.root)
236 if not stat.S_ISDIR(root_st.st_mode):
237 cros_build_lib.Die('root (%s) must be a directory.' % opts.root)
238
239 # Detect the possible locations of the gconv-modules file.
240 gconv_modules_files = glob.glob(os.path.join(opts.root, GCONV_MODULES_PATH))
241
242 if not gconv_modules_files:
Ralph Nathan446aee92015-03-23 14:44:56 -0700243 logging.warning('gconv-modules file not found.')
Alex Deymo2bba3812014-08-13 08:49:09 -0700244 return 1
245
246 # Only one gconv-modules files should be present, either on /usr/lib or
247 # /usr/lib64, but not both.
248 if len(gconv_modules_files) > 1:
249 cros_build_lib.Die('Found several gconv-modules files.')
250
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400251 gconv_modules_file = gconv_modules_files[0]
Ralph Nathan03047282015-03-23 11:09:32 -0700252 logging.info('Searching for unused gconv files defined in %s',
253 gconv_modules_file)
Alex Deymo2bba3812014-08-13 08:49:09 -0700254
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400255 gmods = GconvModules(gconv_modules_file)
Alex Deymo2bba3812014-08-13 08:49:09 -0700256 charsets = gmods.Load()
257
258 # Use scanelf to search for all the binary files on the rootfs that require
259 # or define the symbol iconv_open. We also include the binaries that define
260 # it since there could be internal calls to it from other functions.
261 files = set()
262 for symbol in GCONV_SYMBOLS:
263 cmd = ['scanelf', '--mount', '--quiet', '--recursive', '--format', '#s%F',
264 '--symbol', symbol, opts.root]
265 result = cros_build_lib.RunCommand(cmd, redirect_stdout=True,
266 print_cmd=False)
267 symbol_files = result.output.splitlines()
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700268 logging.debug('Symbol %s found on %d files.', symbol, len(symbol_files))
Alex Deymo2bba3812014-08-13 08:49:09 -0700269 files.update(symbol_files)
270
271 # The charsets are represented as nul-terminated strings in the binary files,
272 # so we append the '\0' to each string. This prevents some false positives
273 # when the name of the charset is a substring of some other string. It doesn't
274 # prevent false positives when the charset name is the suffix of another
275 # string, for example a binary with the string "DON'T DO IT\0" will match the
276 # 'IT' charset. Empirical test on ChromeOS images suggests that only 4
277 # charsets could fall in category.
278 strings = [s + '\0' for s in charsets]
Ralph Nathan03047282015-03-23 11:09:32 -0700279 logging.info('Will search for %d strings in %d files', len(strings),
280 len(files))
Alex Deymo2bba3812014-08-13 08:49:09 -0700281
282 # Charsets listed in STICKY_MOUDLES are initialized as used. Note that those
283 # strings should be listed in the gconv-modules file.
284 unknown_sticky_modules = set(STICKY_MODULES) - set(charsets)
285 if unknown_sticky_modules:
Ralph Nathan446aee92015-03-23 14:44:56 -0700286 logging.warning(
Alex Deymo2bba3812014-08-13 08:49:09 -0700287 'The following charsets were explicitly requested in STICKY_MODULES '
288 'even though they don\'t exist: %s',
289 ', '.join(unknown_sticky_modules))
290 global_used = [charset in STICKY_MODULES for charset in charsets]
291
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400292 for filename in files:
293 used_filename = MultipleStringMatch(strings,
294 osutils.ReadFile(filename, mode='rb'))
Alex Deymo2bba3812014-08-13 08:49:09 -0700295
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400296 global_used = map(operator.or_, global_used, used_filename)
Alex Deymo2bba3812014-08-13 08:49:09 -0700297 # Check the debug flag to avoid running an useless loop.
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400298 if opts.debug and any(used_filename):
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700299 logging.debug('File %s:', filename)
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400300 for i in range(len(used_filename)):
301 if used_filename[i]:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700302 logging.debug(' - %s', strings[i])
Alex Deymo2bba3812014-08-13 08:49:09 -0700303
304 used_charsets = [cs for cs, used in zip(charsets, global_used) if used]
305 gmods.Rewrite(used_charsets, opts.dry_run)
306 return 0
307
308
309def ParseArgs(argv):
310 """Return parsed commandline arguments."""
311
312 parser = commandline.ArgumentParser()
313 parser.add_argument(
314 '--dry-run', action='store_true', default=False,
315 help='process but don\'t modify any file.')
316 parser.add_argument(
317 'root', type='path',
318 help='path to the directory where the rootfs is mounted.')
319
320 opts = parser.parse_args(argv)
321 opts.Freeze()
322 return opts
323
324
325def main(argv):
326 """Main function to start the script."""
327 opts = ParseArgs(argv)
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700328 logging.debug('Options are %s', opts)
Alex Deymo2bba3812014-08-13 08:49:09 -0700329
330 return GconvStrip(opts)