Upstream version 5.34.104.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 sys
10
11 import buildbot_common
12 import build_version
13 import generate_make
14 import parse_dsc
15
16 from build_paths import NACL_DIR, SDK_SRC_DIR, OUT_DIR, SDK_RESOURCE_DIR
17 from build_paths import GSTORE
18 from generate_index import LandingPage
19
20 sys.path.append(os.path.join(SDK_SRC_DIR, 'tools'))
21 sys.path.append(os.path.join(NACL_DIR, 'build'))
22 import getos
23 import http_download
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   # On Windows add a prebuilt make
77   if getos.GetPlatform() == 'win':
78     buildbot_common.BuildStep('Add MAKE')
79     http_download.HttpDownload(GSTORE + MAKE,
80                                os.path.join(tools_dir, 'make.exe'))
81
82
83 def ValidateToolchains(toolchains):
84   invalid_toolchains = set(toolchains) - set(VALID_TOOLCHAINS)
85   if invalid_toolchains:
86     buildbot_common.ErrorExit('Invalid toolchain(s): %s' % (
87         ', '.join(invalid_toolchains)))
88
89
90 def UpdateProjects(pepperdir, project_tree, toolchains,
91                    clobber=False, configs=None, first_toolchain=False):
92   if configs is None:
93     configs = ['Debug', 'Release']
94   if not os.path.exists(os.path.join(pepperdir, 'tools')):
95     buildbot_common.ErrorExit('Examples depend on missing tools.')
96   if not os.path.exists(os.path.join(pepperdir, 'toolchain')):
97     buildbot_common.ErrorExit('Examples depend on missing toolchains.')
98
99   ValidateToolchains(toolchains)
100
101   # Create the library output directories
102   libdir = os.path.join(pepperdir, 'lib')
103   platform = getos.GetPlatform()
104   for config in configs:
105     for arch in LIB_DICT[platform]:
106       dirpath = os.path.join(libdir, '%s_%s_host' % (platform, arch), config)
107       if clobber:
108         buildbot_common.RemoveDir(dirpath)
109       buildbot_common.MakeDir(dirpath)
110
111   landing_page = None
112   for branch, projects in project_tree.iteritems():
113     dirpath = os.path.join(pepperdir, branch)
114     if clobber:
115       buildbot_common.RemoveDir(dirpath)
116     buildbot_common.MakeDir(dirpath)
117     targets = [desc['NAME'] for desc in projects]
118
119     # Generate master make for this branch of projects
120     generate_make.GenerateMasterMakefile(pepperdir,
121                                          os.path.join(pepperdir, branch),
122                                          targets)
123
124     if branch.startswith('examples') and not landing_page:
125       landing_page = LandingPage()
126
127     # Generate individual projects
128     for desc in projects:
129       srcroot = os.path.dirname(desc['FILEPATH'])
130       generate_make.ProcessProject(pepperdir, srcroot, pepperdir, desc,
131                                    toolchains, configs=configs,
132                                    first_toolchain=first_toolchain)
133
134       if branch.startswith('examples'):
135         landing_page.AddDesc(desc)
136
137   if landing_page:
138     # Generate the landing page text file.
139     index_html = os.path.join(pepperdir, 'examples', 'index.html')
140     index_template = os.path.join(SDK_RESOURCE_DIR, 'index.html.template')
141     with open(index_html, 'w') as fh:
142       out = landing_page.GeneratePage(index_template)
143       fh.write(out)
144
145   # Generate top Make for examples
146   targets = ['api', 'demo', 'getting_started', 'tutorial']
147   targets = [x for x in targets if 'examples/'+x in project_tree]
148   branch_name = 'examples'
149   generate_make.GenerateMasterMakefile(pepperdir,
150                                        os.path.join(pepperdir, branch_name),
151                                        targets)
152
153
154 def BuildProjectsBranch(pepperdir, branch, deps, clean, config, args=None):
155   make_dir = os.path.join(pepperdir, branch)
156   print "\nMake: " + make_dir
157
158   if getos.GetPlatform() == 'win':
159     # We need to modify the environment to build host on Windows.
160     make = os.path.join(make_dir, 'make.bat')
161   else:
162     make = 'make'
163
164   env = None
165   if os.environ.get('USE_GOMA') == '1':
166     env = dict(os.environ)
167     env['NACL_COMPILER_PREFIX'] = 'gomacc'
168     # Add -m32 to the CFLAGS when building using i686-nacl-gcc
169     # otherwise goma won't recognise it as different to the x86_64
170     # build.
171     env['X86_32_CFLAGS'] = '-m32'
172     env['X86_32_CXXFLAGS'] = '-m32'
173     jobs = '50'
174   else:
175     jobs = str(multiprocessing.cpu_count())
176
177   make_cmd = [make, '-j', jobs]
178
179   make_cmd.append('CONFIG='+config)
180   if not deps:
181     make_cmd.append('IGNORE_DEPS=1')
182
183   if verbose:
184     make_cmd.append('V=1')
185
186   if args:
187     make_cmd += args
188   else:
189     make_cmd.append('TOOLCHAIN=all')
190
191   buildbot_common.Run(make_cmd, cwd=make_dir, env=env)
192   if clean:
193     # Clean to remove temporary files but keep the built
194     buildbot_common.Run(make_cmd + ['clean'], cwd=make_dir, env=env)
195
196
197 def BuildProjects(pepperdir, project_tree, deps=True,
198                   clean=False, config='Debug'):
199
200   # Make sure we build libraries (which live in 'src') before
201   # any of the examples.
202   build_first = [p for p in project_tree if p != 'src']
203   build_second = [p for p in project_tree if p == 'src']
204
205   for branch in build_first + build_second:
206     BuildProjectsBranch(pepperdir, branch, deps, clean, config)
207
208
209 def main(argv):
210   parser = optparse.OptionParser()
211   parser.add_option('-c', '--clobber',
212       help='Clobber project directories before copying new files',
213       action='store_true', default=False)
214   parser.add_option('-b', '--build',
215       help='Build the projects.', action='store_true')
216   parser.add_option('--config',
217       help='Choose configuration to build (Debug or Release).  Builds both '
218            'by default')
219   parser.add_option('-x', '--experimental',
220       help='Build experimental projects', action='store_true')
221   parser.add_option('-t', '--toolchain',
222       help='Build using toolchain. Can be passed more than once.',
223       action='append', default=[])
224   parser.add_option('-d', '--dest',
225       help='Select which build destinations (project types) are valid.',
226       action='append')
227   parser.add_option('-v', '--verbose', action='store_true')
228
229   # To setup bash completion for this command first install optcomplete
230   # and then add this line to your .bashrc:
231   #  complete -F _optcomplete build_projects.py
232   try:
233     import optcomplete
234     optcomplete.autocomplete(parser)
235   except ImportError:
236     pass
237
238   options, args = parser.parse_args(argv[1:])
239
240   if 'NACL_SDK_ROOT' in os.environ:
241     # We don't want the currently configured NACL_SDK_ROOT to have any effect
242     # on the build.
243     del os.environ['NACL_SDK_ROOT']
244
245   pepper_ver = str(int(build_version.ChromeMajorVersion()))
246   pepperdir = os.path.join(OUT_DIR, 'pepper_' + pepper_ver)
247
248   if not options.toolchain:
249     # Order matters here: the default toolchain for an example's Makefile will
250     # be the first toolchain in this list that is available in the example.
251     # e.g. If an example supports newlib and glibc, then the default will be
252     # newlib.
253     options.toolchain = ['pnacl', 'newlib', 'glibc', 'host']
254     if options.experimental:
255       options.toolchain.append('bionic')
256
257   if 'host' in options.toolchain:
258     options.toolchain.remove('host')
259     options.toolchain.append(getos.GetPlatform())
260     print 'Adding platform: ' + getos.GetPlatform()
261
262   ValidateToolchains(options.toolchain)
263
264   filters = {}
265   if options.toolchain:
266     filters['TOOLS'] = options.toolchain
267     print 'Filter by toolchain: ' + str(options.toolchain)
268   if not options.experimental:
269     filters['EXPERIMENTAL'] = False
270   if options.dest:
271     filters['DEST'] = options.dest
272     print 'Filter by type: ' + str(options.dest)
273   if args:
274     filters['NAME'] = args
275     print 'Filter by name: ' + str(args)
276
277   try:
278     project_tree = parse_dsc.LoadProjectTree(SDK_SRC_DIR, include=filters)
279   except parse_dsc.ValidationError as e:
280     buildbot_common.ErrorExit(str(e))
281   parse_dsc.PrintProjectTree(project_tree)
282
283   UpdateHelpers(pepperdir, clobber=options.clobber)
284   UpdateProjects(pepperdir, project_tree, options.toolchain,
285                  clobber=options.clobber)
286
287   if options.verbose:
288     global verbose
289     verbose = True
290
291   if options.build:
292     if options.config:
293       configs = [options.config]
294     else:
295       configs = ['Debug', 'Release']
296     for config in configs:
297       BuildProjects(pepperdir, project_tree, config=config)
298
299   return 0
300
301
302 if __name__ == '__main__':
303   script_name = os.path.basename(sys.argv[0])
304   try:
305     sys.exit(main(sys.argv))
306   except parse_dsc.ValidationError as e:
307     buildbot_common.ErrorExit('%s: %s' % (script_name, e))
308   except KeyboardInterrupt:
309     buildbot_common.ErrorExit('%s: interrupted' % script_name)