2 # Copyright (c) 2012 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.
6 """This script lays out the PNaCl translator files for a
7 normal Chrome installer, for one platform. Once run num-of-arches times,
8 the result can then be packed into a multi-CRX zip file.
10 This script depends on and pulls in the translator nexes and libraries
11 from the PNaCl translator. It also depends on the pnacl_irt_shim.
26 ######################################################################
27 # Target arch and build arch junk to convert between all the
28 # silly conventions between SCons, Chrome and PNaCl.
30 # The version of the arch used by NaCl manifest files.
31 # This is based on the machine "building" this extension.
32 # We also used this to identify the arch-specific different versions of
35 def CanonicalArch(arch):
36 if arch in ('x86_64', 'x86-64', 'x64', 'amd64'):
38 # TODO(jvoung): be more specific about the arm architecture version?
39 if arch in ('arm', 'armv7'):
41 if arch in ('mipsel'):
43 if re.match('^i.86$', arch) or arch in ('x86_32', 'x86-32', 'ia32', 'x86'):
48 arch = platform.machine()
49 return CanonicalArch(arch)
51 BUILD_ARCH = GetBuildArch()
52 ARCHES = ['x86-32', 'x86-64', 'arm', 'mips32']
54 def IsValidArch(arch):
57 # The version of the arch used by configure and pnacl's build.sh.
58 def StandardArch(arch):
59 return {'x86-32': 'i686',
62 'mips32': 'mips'}[arch]
65 ######################################################################
67 # Normalize the platform name to be the way SCons finds chrome binaries.
68 # This is based on the platform "building" the extension.
70 def GetBuildPlatform():
71 if sys.platform == 'darwin':
73 elif sys.platform.startswith('linux'):
75 elif sys.platform in ('cygwin', 'win32'):
78 raise Exception('Unknown platform: %s' % sys.platform)
80 BUILD_PLATFORM = GetBuildPlatform()
83 def DetermineInstallerArches(target_arch):
84 arch = CanonicalArch(target_arch)
85 if not IsValidArch(arch):
86 raise Exception('Unknown target_arch %s' % target_arch)
87 # On windows, we need x86-32 and x86-64 (assuming non-windows RT).
88 if BUILD_PLATFORM == 'windows':
89 if arch.startswith('x86'):
90 return ['x86-32', 'x86-64']
92 raise Exception('Unknown target_arch on windows w/ target_arch == %s' %
98 ######################################################################
100 class PnaclPackaging(object):
102 package_base = os.path.dirname(__file__)
104 # File paths that are set from the command line.
105 pnacl_template = None
106 package_version_path = None
107 pnacl_package = 'pnacl_newlib'
109 # Agreed-upon name for pnacl-specific info.
110 pnacl_json = 'pnacl.json'
113 def SetPnaclInfoTemplatePath(path):
114 PnaclPackaging.pnacl_template = path
117 def SetPackageVersionPath(path):
118 PnaclPackaging.package_version_path = path
121 def SetPnaclPackageName(name):
122 PnaclPackaging.pnacl_package = name
125 def PnaclToolsRevision():
126 pkg_ver_cmd = [sys.executable, PnaclPackaging.package_version_path,
128 '--revision-package', PnaclPackaging.pnacl_package]
130 version = subprocess.check_output(pkg_ver_cmd).strip()
132 # CWS happens to use version quads, so make it a quad too.
133 # However, each component of the quad is limited to 64K max.
134 # Try to handle a bit more.
135 max_version = 2 ** 16
136 version = int(version)
137 version_more = version / max_version
138 version = version % max_version
139 return '0.1.%d.%d' % (version_more, version)
142 def GeneratePnaclInfo(target_dir, abi_version, arch):
143 # A note on versions: pnacl_version is the version of translator built
144 # by the NaCl repo, while abi_version is bumped when the NaCl sandbox
146 pnacl_version = PnaclPackaging.PnaclToolsRevision()
147 with open(PnaclPackaging.pnacl_template, 'r') as pnacl_template_fd:
148 pnacl_template = json.load(pnacl_template_fd)
149 out_name = J(target_dir, UseWhitelistedChars(PnaclPackaging.pnacl_json,
151 with open(out_name, 'w') as output_fd:
152 pnacl_template['pnacl-arch'] = arch
153 pnacl_template['pnacl-version'] = pnacl_version
154 json.dump(pnacl_template, output_fd, sort_keys=True, indent=4)
157 ######################################################################
159 class PnaclDirs(object):
160 translator_dir = None
164 def SetTranslatorRoot(d):
165 PnaclDirs.translator_dir = d
168 def TranslatorRoot():
169 return PnaclDirs.translator_dir
172 def LibDir(target_arch):
173 return J(PnaclDirs.TranslatorRoot(), 'lib-%s' % target_arch)
176 def SandboxedCompilerDir(target_arch):
177 return J(PnaclDirs.TranslatorRoot(), StandardArch(target_arch), 'bin')
181 PnaclDirs.output_dir = d
185 return PnaclDirs.output_dir
188 def OutputAllDir(version_quad):
189 return J(PnaclDirs.OutputDir(), version_quad)
192 def OutputArchBase(arch):
196 def OutputArchDir(arch):
197 # Nest this in another directory so that the layout will be the same
198 # as the "all"/universal version.
199 parent_dir = J(PnaclDirs.OutputDir(), PnaclDirs.OutputArchBase(arch))
200 return (parent_dir, J(parent_dir, PnaclDirs.OutputArchBase(arch)))
203 ######################################################################
205 def StepBanner(short_desc, long_desc):
206 logging.info("**** %s\t%s", short_desc, long_desc)
210 out_dir = PnaclDirs.OutputDir()
211 StepBanner('CLEAN', 'Cleaning out old packaging: %s' % out_dir)
212 if os.path.isdir(out_dir):
213 shutil.rmtree(out_dir)
215 logging.info('Clean skipped -- no previous output directory!')
217 ######################################################################
219 def UseWhitelistedChars(orig_basename, arch):
220 """ Make the filename match the pattern expected by nacl_file_host.
222 Currently, this assumes there is prefix "pnacl_public_" and
223 that the allowed chars are in the set [a-zA-Z0-9_].
226 target_basename = 'pnacl_public_%s_%s' % (arch, orig_basename)
228 target_basename = 'pnacl_public_%s' % orig_basename
229 result = re.sub(r'[^a-zA-Z0-9_]', '_', target_basename)
230 logging.info('UseWhitelistedChars using: %s' % result)
233 def CopyFlattenDirsAndPrefix(src_dir, arch, dest_dir):
234 """ Copy files from src_dir to dest_dir.
236 When copying, also rename the files such that they match the white-listing
237 pattern in chrome/browser/nacl_host/nacl_file_host.cc.
239 if not os.path.isdir(src_dir):
240 raise Exception('Copy dir failed, directory does not exist: %s' % src_dir)
242 for (root, dirs, files) in os.walk(src_dir, followlinks=True):
244 # Assume a flat directory.
245 assert (f == os.path.basename(f))
246 full_name = J(root, f)
247 target_name = UseWhitelistedChars(f, arch)
248 shutil.copy(full_name, J(dest_dir, target_name))
251 def BuildArchForInstaller(version_quad, arch, lib_overrides):
252 """ Build an architecture specific version for the chrome installer.
254 target_dir = PnaclDirs.OutputDir()
256 StepBanner('BUILD INSTALLER',
257 'Packaging for arch %s in %s' % (arch, target_dir))
259 # Copy llc.nexe and ld.nexe, but with some renaming and directory flattening.
260 CopyFlattenDirsAndPrefix(PnaclDirs.SandboxedCompilerDir(arch),
264 # Copy native libraries, also with renaming and directory flattening.
265 CopyFlattenDirsAndPrefix(PnaclDirs.LibDir(arch), arch, target_dir)
267 # Also copy files from the list of overrides.
268 # This needs the arch tagged onto the name too, like the other files.
269 if arch in lib_overrides:
270 for override in lib_overrides[arch]:
271 override_base = os.path.basename(override)
272 target_name = UseWhitelistedChars(override_base, arch)
273 shutil.copy(override, J(target_dir, target_name))
276 def BuildInstallerStyle(version_quad, lib_overrides, arches):
277 """ Package the pnacl component for use within the chrome installer
278 infrastructure. These files need to be named in a special way
279 so that white-listing of files is easy.
281 StepBanner("BUILD_ALL", "Packaging installer for version: %s" % version_quad)
283 BuildArchForInstaller(version_quad, arch, lib_overrides)
284 # Generate pnacl info manifest.
285 # Hack around the fact that there may be more than one arch, on Windows.
288 PnaclPackaging.GeneratePnaclInfo(PnaclDirs.OutputDir(), version_quad, arches)
291 ######################################################################
295 usage = 'usage: %prog [options] version_arg'
296 parser = optparse.OptionParser(usage)
297 # We may want to accept a target directory to dump it in the usual
298 # output directory (e.g., scons-out).
299 parser.add_option('-c', '--clean', dest='clean',
300 action='store_true', default=False,
301 help='Clean out destination directory first.')
302 parser.add_option('-d', '--dest', dest='dest',
303 help='The destination root for laying out the extension')
304 parser.add_option('-L', '--lib_override',
305 dest='lib_overrides', action='append', default=[],
306 help='Specify path to a fresher native library ' +
307 'that overrides the tarball library with ' +
308 '(arch:libfile) tuple.')
309 parser.add_option('-t', '--target_arch',
310 dest='target_arch', default=None,
311 help='Only generate the chrome installer version for arch')
312 parser.add_option('--info_template_path',
313 dest='info_template_path', default=None,
314 help='Path of the info template file')
315 parser.add_option('--package_version_path', dest='package_version_path',
316 default=None, help='Path to package_version.py script.')
317 parser.add_option('--pnacl_package_name', dest='pnacl_package_name',
318 default=None, help='Name of PNaCl package.')
319 parser.add_option('--pnacl_translator_path', dest='pnacl_translator_path',
320 default=None, help='Location of PNaCl translator.')
321 parser.add_option('-v', '--verbose', dest='verbose', default=False,
323 help='Print verbose debug messages.')
325 (options, args) = parser.parse_args()
327 logging.getLogger().setLevel(logging.DEBUG)
329 logging.getLogger().setLevel(logging.ERROR)
330 logging.info('pnacl_component_crx_gen w/ options %s and args %s\n'
333 # Set destination directory before doing any cleaning, etc.
334 if options.dest is None:
335 raise Exception('Destination path must be set.')
336 PnaclDirs.SetOutputDir(options.dest)
341 if options.pnacl_translator_path is None:
342 raise Exception('PNaCl translator path must be set.')
343 PnaclDirs.SetTranslatorRoot(options.pnacl_translator_path)
345 if options.info_template_path:
346 PnaclPackaging.SetPnaclInfoTemplatePath(options.info_template_path)
348 if options.package_version_path:
349 PnaclPackaging.SetPackageVersionPath(options.package_version_path)
351 raise Exception('Package verison script must be specified.')
353 if options.pnacl_package_name:
354 PnaclPackaging.SetPnaclPackageName(options.pnacl_package_name)
357 for o in options.lib_overrides:
358 arch, override_lib = o.split(',')
359 arch = CanonicalArch(arch)
360 if not IsValidArch(arch):
361 raise Exception('Unknown arch for -L: %s (from %s)' % (arch, o))
362 if not os.path.isfile(override_lib):
363 raise Exception('Override native lib not a file for -L: %s (from %s)' %
365 override_list = lib_overrides.get(arch, [])
366 override_list.append(override_lib)
367 lib_overrides[arch] = override_list
371 parser.error('Incorrect number of arguments')
373 abi_version = int(args[0])
375 arches = DetermineInstallerArches(options.target_arch)
376 BuildInstallerStyle(abi_version, lib_overrides, arches)
380 if __name__ == '__main__':