Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / native_client_sdk / src / build_tools / build_projects.py
1 #!/usr/bin/env python
2 # Copyright (c) 2013 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 import multiprocessing
7 import optparse
8 import os
9 import posixpath
10 import sys
11 import urllib2
12
13 import buildbot_common
14 import build_version
15 import generate_make
16 import parse_dsc
17
18 from build_paths import SDK_SRC_DIR, OUT_DIR, SDK_RESOURCE_DIR
19 from build_paths import GSTORE
20 from generate_index import LandingPage
21
22 sys.path.append(os.path.join(SDK_SRC_DIR, 'tools'))
23 import getos
24
25
26 MAKE = 'nacl_sdk/make_3.99.90-26-gf80222c/make.exe'
27 LIB_DICT = {
28   'linux': [],
29   'mac': [],
30   'win': ['x86_32']
31 }
32 VALID_TOOLCHAINS = [
33   'bionic',
34   'newlib',
35   'glibc',
36   'pnacl',
37   'win',
38   'linux',
39   'mac',
40 ]
41
42 # Global verbosity setting.
43 # If set to try (normally via a command line arg) then build_projects will
44 # add V=1 to all calls to 'make'
45 verbose = False
46
47
48 def CopyFilesFromTo(filelist, srcdir, dstdir):
49   for filename in filelist:
50     srcpath = os.path.join(srcdir, filename)
51     dstpath = os.path.join(dstdir, filename)
52     buildbot_common.CopyFile(srcpath, dstpath)
53
54
55 def UpdateHelpers(pepperdir, clobber=False):
56   tools_dir = os.path.join(pepperdir, 'tools')
57   if not os.path.exists(tools_dir):
58     buildbot_common.ErrorExit('SDK tools dir is missing: %s' % tools_dir)
59
60   exampledir = os.path.join(pepperdir, 'examples')
61   if clobber:
62     buildbot_common.RemoveDir(exampledir)
63   buildbot_common.MakeDir(exampledir)
64
65   # Copy files for individual build and landing page
66   files = ['favicon.ico', 'httpd.cmd', 'index.css', 'index.js',
67       'button_close.png', 'button_close_hover.png']
68   CopyFilesFromTo(files, SDK_RESOURCE_DIR, exampledir)
69
70   # Copy tools scripts and make includes
71   buildbot_common.CopyDir(os.path.join(SDK_SRC_DIR, 'tools', '*.py'),
72       tools_dir)
73   buildbot_common.CopyDir(os.path.join(SDK_SRC_DIR, 'tools', '*.mk'),
74       tools_dir)
75
76   # Copy tools/lib scripts
77   tools_lib_dir = os.path.join(pepperdir, 'tools', 'lib')
78   buildbot_common.MakeDir(tools_lib_dir)
79   buildbot_common.CopyDir(os.path.join(SDK_SRC_DIR, 'tools', 'lib', '*.py'),
80       tools_lib_dir)
81
82   # On Windows add a prebuilt make
83   if getos.GetPlatform() == 'win':
84     buildbot_common.BuildStep('Add MAKE')
85     make_url = posixpath.join(GSTORE, MAKE)
86     make_exe = os.path.join(tools_dir, 'make.exe')
87     with open(make_exe, 'wb') as f:
88       f.write(urllib2.urlopen(make_url).read())
89
90
91 def ValidateToolchains(toolchains):
92   invalid_toolchains = set(toolchains) - set(VALID_TOOLCHAINS)
93   if invalid_toolchains:
94     buildbot_common.ErrorExit('Invalid toolchain(s): %s' % (
95         ', '.join(invalid_toolchains)))
96
97 def GetDeps(projects):
98   out = {}
99
100   # Build list of all project names
101   localtargets = [proj['NAME'] for proj in projects]
102
103   # For each project
104   for proj in projects:
105     deplist = []
106     # generate a list of dependencies
107     for targ in proj.get('TARGETS', []):
108       deplist.extend(targ.get('DEPS', []) + targ.get('LIBS', []))
109
110     # and add dependencies to targets built in this subtree
111     localdeps = [dep for dep in deplist if dep in localtargets]
112     if localdeps:
113       out[proj['NAME']] = localdeps
114
115   return out
116
117
118 def UpdateProjects(pepperdir, project_tree, toolchains,
119                    clobber=False, configs=None, first_toolchain=False):
120   if configs is None:
121     configs = ['Debug', 'Release']
122   if not os.path.exists(os.path.join(pepperdir, 'tools')):
123     buildbot_common.ErrorExit('Examples depend on missing tools.')
124   if not os.path.exists(os.path.join(pepperdir, 'toolchain')):
125     buildbot_common.ErrorExit('Examples depend on missing toolchains.')
126
127   ValidateToolchains(toolchains)
128
129   # Create the library output directories
130   libdir = os.path.join(pepperdir, 'lib')
131   platform = getos.GetPlatform()
132   for config in configs:
133     for arch in LIB_DICT[platform]:
134       dirpath = os.path.join(libdir, '%s_%s_host' % (platform, arch), config)
135       if clobber:
136         buildbot_common.RemoveDir(dirpath)
137       buildbot_common.MakeDir(dirpath)
138
139   landing_page = None
140   for branch, projects in project_tree.iteritems():
141     dirpath = os.path.join(pepperdir, branch)
142     if clobber:
143       buildbot_common.RemoveDir(dirpath)
144     buildbot_common.MakeDir(dirpath)
145     targets = [desc['NAME'] for desc in projects]
146     deps = GetDeps(projects)
147
148     # Generate master make for this branch of projects
149     generate_make.GenerateMasterMakefile(pepperdir,
150                                          os.path.join(pepperdir, branch),
151                                          targets, deps)
152
153     if branch.startswith('examples') and not landing_page:
154       landing_page = LandingPage()
155
156     # Generate individual projects
157     for desc in projects:
158       srcroot = os.path.dirname(desc['FILEPATH'])
159       generate_make.ProcessProject(pepperdir, srcroot, pepperdir, desc,
160                                    toolchains, configs=configs,
161                                    first_toolchain=first_toolchain)
162
163       if branch.startswith('examples'):
164         landing_page.AddDesc(desc)
165
166   if landing_page:
167     # Generate the landing page text file.
168     index_html = os.path.join(pepperdir, 'examples', 'index.html')
169     index_template = os.path.join(SDK_RESOURCE_DIR, 'index.html.template')
170     with open(index_html, 'w') as fh:
171       out = landing_page.GeneratePage(index_template)
172       fh.write(out)
173
174   # Generate top Make for examples
175   targets = ['api', 'demo', 'getting_started', 'tutorial']
176   targets = [x for x in targets if 'examples/'+x in project_tree]
177   branch_name = 'examples'
178   generate_make.GenerateMasterMakefile(pepperdir,
179                                        os.path.join(pepperdir, branch_name),
180                                        targets, {})
181
182
183 def BuildProjectsBranch(pepperdir, branch, deps, clean, config, args=None):
184   make_dir = os.path.join(pepperdir, branch)
185   print "\nMake: " + make_dir
186
187   if getos.GetPlatform() == 'win':
188     # We need to modify the environment to build host on Windows.
189     make = os.path.join(make_dir, 'make.bat')
190   else:
191     make = 'make'
192
193   env = None
194   if os.environ.get('USE_GOMA') == '1':
195     env = dict(os.environ)
196     env['NACL_COMPILER_PREFIX'] = 'gomacc'
197     # Add -m32 to the CFLAGS when building using i686-nacl-gcc
198     # otherwise goma won't recognise it as different to the x86_64
199     # build.
200     env['X86_32_CFLAGS'] = '-m32'
201     env['X86_32_CXXFLAGS'] = '-m32'
202     jobs = '50'
203   else:
204     jobs = str(multiprocessing.cpu_count())
205
206   make_cmd = [make, '-j', jobs]
207
208   make_cmd.append('CONFIG='+config)
209   # We always ENABLE_BIONIC in case we need it.  If neither --bionic nor
210   # -t bionic have been provided on the command line, then VALID_TOOLCHAINS
211   # will not contain a bionic target.
212   make_cmd.append('ENABLE_BIONIC=1')
213   if not deps:
214     make_cmd.append('IGNORE_DEPS=1')
215
216   if verbose:
217     make_cmd.append('V=1')
218
219   if args:
220     make_cmd += args
221   else:
222     make_cmd.append('TOOLCHAIN=all')
223
224   buildbot_common.Run(make_cmd, cwd=make_dir, env=env)
225   if clean:
226     # Clean to remove temporary files but keep the built
227     buildbot_common.Run(make_cmd + ['clean'], cwd=make_dir, env=env)
228
229
230 def BuildProjects(pepperdir, project_tree, deps=True,
231                   clean=False, config='Debug'):
232
233   # Make sure we build libraries (which live in 'src') before
234   # any of the examples.
235   build_first = [p for p in project_tree if p != 'src']
236   build_second = [p for p in project_tree if p == 'src']
237
238   for branch in build_first + build_second:
239     BuildProjectsBranch(pepperdir, branch, deps, clean, config)
240
241
242 def main(argv):
243   parser = optparse.OptionParser()
244   parser.add_option('-c', '--clobber',
245       help='Clobber project directories before copying new files',
246       action='store_true', default=False)
247   parser.add_option('-b', '--build',
248       help='Build the projects.', action='store_true')
249   parser.add_option('--config',
250       help='Choose configuration to build (Debug or Release).  Builds both '
251            'by default')
252   parser.add_option('--bionic',
253       help='Enable bionic projects', action='store_true')
254   parser.add_option('-x', '--experimental',
255       help='Build experimental projects', action='store_true')
256   parser.add_option('-t', '--toolchain',
257       help='Build using toolchain. Can be passed more than once.',
258       action='append', default=[])
259   parser.add_option('-d', '--dest',
260       help='Select which build destinations (project types) are valid.',
261       action='append')
262   parser.add_option('-v', '--verbose', action='store_true')
263
264   # To setup bash completion for this command first install optcomplete
265   # and then add this line to your .bashrc:
266   #  complete -F _optcomplete build_projects.py
267   try:
268     import optcomplete
269     optcomplete.autocomplete(parser)
270   except ImportError:
271     pass
272
273   options, args = parser.parse_args(argv[1:])
274
275   if 'NACL_SDK_ROOT' in os.environ:
276     # We don't want the currently configured NACL_SDK_ROOT to have any effect
277     # on the build.
278     del os.environ['NACL_SDK_ROOT']
279
280   pepper_ver = str(int(build_version.ChromeMajorVersion()))
281   pepperdir = os.path.join(OUT_DIR, 'pepper_' + pepper_ver)
282
283   if not options.toolchain:
284     # Order matters here: the default toolchain for an example's Makefile will
285     # be the first toolchain in this list that is available in the example.
286     # e.g. If an example supports newlib and glibc, then the default will be
287     # newlib.
288     options.toolchain = ['pnacl', 'newlib', 'glibc', 'host']
289     if options.experimental or options.bionic:
290       options.toolchain.append('bionic')
291
292   if 'host' in options.toolchain:
293     options.toolchain.remove('host')
294     options.toolchain.append(getos.GetPlatform())
295     print 'Adding platform: ' + getos.GetPlatform()
296
297   ValidateToolchains(options.toolchain)
298
299   filters = {}
300   if options.toolchain:
301     filters['TOOLS'] = options.toolchain
302     print 'Filter by toolchain: ' + str(options.toolchain)
303   if not options.experimental:
304     filters['EXPERIMENTAL'] = False
305   if options.dest:
306     filters['DEST'] = options.dest
307     print 'Filter by type: ' + str(options.dest)
308   if args:
309     filters['NAME'] = args
310     print 'Filter by name: ' + str(args)
311
312   try:
313     project_tree = parse_dsc.LoadProjectTree(SDK_SRC_DIR, include=filters)
314   except parse_dsc.ValidationError as e:
315     buildbot_common.ErrorExit(str(e))
316   parse_dsc.PrintProjectTree(project_tree)
317
318   UpdateHelpers(pepperdir, clobber=options.clobber)
319   UpdateProjects(pepperdir, project_tree, options.toolchain,
320                  clobber=options.clobber)
321
322   if options.verbose:
323     global verbose
324     verbose = True
325
326   if options.build:
327     if options.config:
328       configs = [options.config]
329     else:
330       configs = ['Debug', 'Release']
331     for config in configs:
332       BuildProjects(pepperdir, project_tree, config=config)
333
334   return 0
335
336
337 if __name__ == '__main__':
338   script_name = os.path.basename(sys.argv[0])
339   try:
340     sys.exit(main(sys.argv))
341   except parse_dsc.ValidationError as e:
342     buildbot_common.ErrorExit('%s: %s' % (script_name, e))
343   except KeyboardInterrupt:
344     buildbot_common.ErrorExit('%s: interrupted' % script_name)