blob: 62caefc68c96ea63e4428399a06e9a184091e339 [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:
100 cros_build_lib.Error('charset "%s" already defined as "%s".',
101 fromset, self._alias[fromset])
102 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
172 cros_build_lib.Info(
173 'Done. Using %d gconv modules. Removed %d unused modules'
174 ' (%.1f KiB) and %d unused dependencies (%.1f KiB)',
175 len(used_modules), len(unused_modules), unused_size / 1024.,
176 len(unused_libdeps), unused_libdeps_size / 1024.)
Alex Deymo2bba3812014-08-13 08:49:09 -0700177
178 # Recompute the gconv-modules file with only the included gconv modules.
179 result = []
180 for line in open(self._filename):
181 lst = line.split('#', 1)[0].strip().split()
182
183 if not lst:
184 result.append(line) # Keep comments and copyright headers.
185 elif lst[0] == 'module':
186 _, _, _, filename = lst[:4]
187 if filename in used_modules:
188 result.append(line) # Used module
189 elif lst[0] == 'alias':
190 _, charset, _ = lst
191 charset = charset.rstrip('/')
192 while charset in self._alias:
193 charset = self._alias[charset]
194 if used_modules.intersection(self._modules[charset]):
195 result.append(line) # Alias to an used module
196 else:
197 cros_build_lib.Die('Unknown line: %s', line)
198
199 if not dry_run:
200 osutils.WriteFile(self._filename, ''.join(result))
201
202
203def MultipleStringMatch(patterns, corpus):
204 """Search a list of strings in a corpus string.
205
206 Args:
207 patterns: A list of strings.
208 corpus: The text where to search for the strings.
209
210 Result:
211 A list of Booleans stating whether each pattern string was found in the
212 corpus or not.
213 """
214 tree = ahocorasick.KeywordTree()
215 for word in patterns:
216 tree.add(word)
217 tree.make()
218
219 result = [False] * len(patterns)
220 for i, j in tree.findall(corpus):
221 match = corpus[i:j]
222 result[patterns.index(match)] = True
223
224 return result
225
226
227def GconvStrip(opts):
228 """Process gconv-modules and remove unused modules.
229
230 Args:
231 opts: The command-line args passed to the script.
232
233 Returns:
234 The exit code number indicating whether the process succeeded.
235 """
236 root_st = os.lstat(opts.root)
237 if not stat.S_ISDIR(root_st.st_mode):
238 cros_build_lib.Die('root (%s) must be a directory.' % opts.root)
239
240 # Detect the possible locations of the gconv-modules file.
241 gconv_modules_files = glob.glob(os.path.join(opts.root, GCONV_MODULES_PATH))
242
243 if not gconv_modules_files:
244 cros_build_lib.Warning('gconv-modules file not found.')
245 return 1
246
247 # Only one gconv-modules files should be present, either on /usr/lib or
248 # /usr/lib64, but not both.
249 if len(gconv_modules_files) > 1:
250 cros_build_lib.Die('Found several gconv-modules files.')
251
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400252 gconv_modules_file = gconv_modules_files[0]
Alex Deymo2bba3812014-08-13 08:49:09 -0700253 cros_build_lib.Info('Searching for unused gconv files defined in %s',
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400254 gconv_modules_file)
Alex Deymo2bba3812014-08-13 08:49:09 -0700255
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400256 gmods = GconvModules(gconv_modules_file)
Alex Deymo2bba3812014-08-13 08:49:09 -0700257 charsets = gmods.Load()
258
259 # Use scanelf to search for all the binary files on the rootfs that require
260 # or define the symbol iconv_open. We also include the binaries that define
261 # it since there could be internal calls to it from other functions.
262 files = set()
263 for symbol in GCONV_SYMBOLS:
264 cmd = ['scanelf', '--mount', '--quiet', '--recursive', '--format', '#s%F',
265 '--symbol', symbol, opts.root]
266 result = cros_build_lib.RunCommand(cmd, redirect_stdout=True,
267 print_cmd=False)
268 symbol_files = result.output.splitlines()
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700269 logging.debug('Symbol %s found on %d files.', symbol, len(symbol_files))
Alex Deymo2bba3812014-08-13 08:49:09 -0700270 files.update(symbol_files)
271
272 # The charsets are represented as nul-terminated strings in the binary files,
273 # so we append the '\0' to each string. This prevents some false positives
274 # when the name of the charset is a substring of some other string. It doesn't
275 # prevent false positives when the charset name is the suffix of another
276 # string, for example a binary with the string "DON'T DO IT\0" will match the
277 # 'IT' charset. Empirical test on ChromeOS images suggests that only 4
278 # charsets could fall in category.
279 strings = [s + '\0' for s in charsets]
280 cros_build_lib.Info('Will search for %d strings in %d files',
281 len(strings), len(files))
282
283 # Charsets listed in STICKY_MOUDLES are initialized as used. Note that those
284 # strings should be listed in the gconv-modules file.
285 unknown_sticky_modules = set(STICKY_MODULES) - set(charsets)
286 if unknown_sticky_modules:
287 cros_build_lib.Warning(
288 'The following charsets were explicitly requested in STICKY_MODULES '
289 'even though they don\'t exist: %s',
290 ', '.join(unknown_sticky_modules))
291 global_used = [charset in STICKY_MODULES for charset in charsets]
292
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400293 for filename in files:
294 used_filename = MultipleStringMatch(strings,
295 osutils.ReadFile(filename, mode='rb'))
Alex Deymo2bba3812014-08-13 08:49:09 -0700296
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400297 global_used = map(operator.or_, global_used, used_filename)
Alex Deymo2bba3812014-08-13 08:49:09 -0700298 # Check the debug flag to avoid running an useless loop.
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400299 if opts.debug and any(used_filename):
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700300 logging.debug('File %s:', filename)
Mike Frysinger22f6c5a2014-08-18 00:45:54 -0400301 for i in range(len(used_filename)):
302 if used_filename[i]:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700303 logging.debug(' - %s', strings[i])
Alex Deymo2bba3812014-08-13 08:49:09 -0700304
305 used_charsets = [cs for cs, used in zip(charsets, global_used) if used]
306 gmods.Rewrite(used_charsets, opts.dry_run)
307 return 0
308
309
310def ParseArgs(argv):
311 """Return parsed commandline arguments."""
312
313 parser = commandline.ArgumentParser()
314 parser.add_argument(
315 '--dry-run', action='store_true', default=False,
316 help='process but don\'t modify any file.')
317 parser.add_argument(
318 'root', type='path',
319 help='path to the directory where the rootfs is mounted.')
320
321 opts = parser.parse_args(argv)
322 opts.Freeze()
323 return opts
324
325
326def main(argv):
327 """Main function to start the script."""
328 opts = ParseArgs(argv)
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700329 logging.debug('Options are %s', opts)
Alex Deymo2bba3812014-08-13 08:49:09 -0700330
331 return GconvStrip(opts)