summaryrefslogtreecommitdiffstats
path: root/native_client_sdk/src/build_tools/generate_make.py
blob: 17fbcc904d596e37df969b74ac701b7aa98114bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import json
import os
import sys

import buildbot_common
import build_version
import getos
from buildbot_common import ErrorExit
from easy_template import RunTemplateFileIfChanged
from build_paths import SDK_RESOURCE_DIR

def Trace(msg):
  if Trace.verbose:
    sys.stderr.write(str(msg) + '\n')
Trace.verbose = False


def IsExample(desc):
  dest = desc['DEST']
  return dest.startswith('examples') or dest.startswith('tests')


def GenerateSourceCopyList(desc):
  sources = []
  # Add sources for each target
  for target in desc['TARGETS']:
    sources.extend(target['SOURCES'])

  # And HTML and data files
  sources.extend(desc.get('DATA', []))

  if IsExample(desc):
    sources.extend(['common.js', 'icon128.png', 'background.js'])

  return sources


def GetSourcesDict(sources):
  source_map = {}
  for key in ['.c', '.cc']:
    source_list = [fname for fname in sources if fname.endswith(key)]
    if source_list:
      source_map[key] = source_list
    else:
      source_map[key] = []
  return source_map


def GetProjectObjects(source_dict):
  object_list = []
  for key in ['.c', '.cc']:
    for src in source_dict[key]:
      object_list.append(os.path.splitext(src)[0])
  return object_list


def GetPlatforms(plat_list, plat_filter, first_toolchain):
  platforms = []
  for plat in plat_list:
    if plat in plat_filter:
      platforms.append(plat)

  if first_toolchain:
    return [platforms[0]]
  return platforms


def ErrorMsgFunc(text):
  sys.stderr.write(text + '\n')


def AddMakeBat(pepperdir, makepath):
  """Create a simple batch file to execute Make.

  Creates a simple batch file named make.bat for the Windows platform at the
  given path, pointing to the Make executable in the SDK."""

  makepath = os.path.abspath(makepath)
  if not makepath.startswith(pepperdir):
    ErrorExit('Make.bat not relative to Pepper directory: ' + makepath)

  makeexe = os.path.abspath(os.path.join(pepperdir, 'tools'))
  relpath = os.path.relpath(makeexe, makepath)

  fp = open(os.path.join(makepath, 'make.bat'), 'wb')
  outpath = os.path.join(relpath, 'make.exe')

  # Since make.bat is only used by Windows, for Windows path style
  outpath = outpath.replace(os.path.sep, '\\')
  fp.write('@%s %%*\n' % outpath)
  fp.close()


def FindFile(name, srcroot, srcdirs):
  checks = []
  for srcdir in srcdirs:
    srcfile = os.path.join(srcroot, srcdir, name)
    srcfile = os.path.abspath(srcfile)
    if os.path.exists(srcfile):
      return srcfile
    else:
      checks.append(srcfile)

  ErrorMsgFunc('%s not found in:\n\t%s' % (name, '\n\t'.join(checks)))
  return None


def IsNexe(desc):
  for target in desc['TARGETS']:
    if target['TYPE'] == 'main':
      return True
  return False


def ProcessHTML(srcroot, dstroot, desc, toolchains, configs, first_toolchain):
  name = desc['NAME']
  nmf = desc['TARGETS'][0]['NAME']
  outdir = os.path.join(dstroot, desc['DEST'], name)
  srcpath = os.path.join(srcroot, 'index.html')
  dstpath = os.path.join(outdir, 'index.html')

  tools = GetPlatforms(toolchains, desc['TOOLS'], first_toolchain)

  path = "{tc}/{config}"
  replace = {
    'title': desc['TITLE'],
    'attrs':
        'data-name="%s" data-tools="%s" data-configs="%s" data-path="%s"' % (
        nmf, ' '.join(tools), ' '.join(configs), path),
  }
  RunTemplateFileIfChanged(srcpath, dstpath, replace)


def GenerateManifest(srcroot, dstroot, desc):
  outdir = os.path.join(dstroot, desc['DEST'], desc['NAME'])
  srcpath = os.path.join(SDK_RESOURCE_DIR, 'manifest.json.template')
  dstpath = os.path.join(outdir, 'manifest.json')
  permissions = desc.get('PERMISSIONS', [])
  socket_permissions = desc.get('SOCKET_PERMISSIONS', [])
  combined_permissions = list(permissions)
  if socket_permissions:
    combined_permissions.append({'socket': socket_permissions})
  pretty_permissions = json.dumps(combined_permissions,
                                  sort_keys=True, indent=4)
  replace = {
      'name': desc['TITLE'],
      'description': '%s Example' % desc['TITLE'],
      'key': True,
      'permissions': pretty_permissions,
      'version': build_version.ChromeVersionNoTrunk()
  }
  RunTemplateFileIfChanged(srcpath, dstpath, replace)


def FindAndCopyFiles(src_files, root, search_dirs, dst_dir):
  buildbot_common.MakeDir(dst_dir)
  for src_name in src_files:
    src_file = FindFile(src_name, root, search_dirs)
    if not src_file:
      ErrorExit('Failed to find: ' + src_name)
    dst_file = os.path.join(dst_dir, src_name)
    if os.path.exists(dst_file):
      if os.stat(src_file).st_mtime <= os.stat(dst_file).st_mtime:
        Trace('Skipping "%s", destination "%s" is newer.' % (
            src_file, dst_file))
        continue
    dst_path = os.path.dirname(dst_file)
    if not os.path.exists(dst_path):
      buildbot_common.MakeDir(dst_path)
    buildbot_common.CopyFile(src_file, dst_file)


def ProcessProject(pepperdir, srcroot, dstroot, desc, toolchains, configs=None,
                   first_toolchain=False):
  if not configs:
    configs = ['Debug', 'Release']

  name = desc['NAME']
  out_dir = os.path.join(dstroot, desc['DEST'], name)
  buildbot_common.MakeDir(out_dir)
  srcdirs = desc.get('SEARCH', ['.', SDK_RESOURCE_DIR])

  # Copy sources to example directory
  sources = GenerateSourceCopyList(desc)
  FindAndCopyFiles(sources, srcroot, srcdirs, out_dir)

  # Copy public headers to the include directory.
  for headers_set in desc.get('HEADERS', []):
    headers = headers_set['FILES']
    header_out_dir = os.path.join(dstroot, headers_set['DEST'])
    FindAndCopyFiles(headers, srcroot, srcdirs, header_out_dir)

  make_path = os.path.join(out_dir, 'Makefile')

  if IsNexe(desc):
    template = os.path.join(SDK_RESOURCE_DIR, 'Makefile.example.template')
  else:
    template = os.path.join(SDK_RESOURCE_DIR, 'Makefile.library.template')

  # Ensure the order of |tools| is the same as toolchains; that way if
  # first_toolchain is set, it will choose based on the order of |toolchains|.
  tools = [tool for tool in toolchains if tool in desc['TOOLS']]
  if first_toolchain:
    tools = [tools[0]]
  for target in desc['TARGETS']:
    target.setdefault('CXXFLAGS', [])
    target['CXXFLAGS'].insert(0, '-Wall')

  template_dict = {
    'rel_sdk': '/'.join(['..'] * (len(desc['DEST'].split('/')) + 1)),
    'pre': desc.get('PRE', ''),
    'post': desc.get('POST', ''),
    'tools': tools,
    'targets': desc['TARGETS'],
  }
  RunTemplateFileIfChanged(template, make_path, template_dict)

  outdir = os.path.dirname(os.path.abspath(make_path))
  if getos.GetPlatform() == 'win':
    AddMakeBat(pepperdir, outdir)

  if IsExample(desc):
    ProcessHTML(srcroot, dstroot, desc, toolchains, configs,
                first_toolchain)
    GenerateManifest(srcroot, dstroot, desc)

  return (name, desc['DEST'])


def GenerateMasterMakefile(pepperdir, out_path, targets):
  """Generate a Master Makefile that builds all examples.

  Args:
    pepperdir: NACL_SDK_ROOT
    out_path: Root for output such that out_path+NAME = full path
    targets: List of targets names
  """
  in_path = os.path.join(SDK_RESOURCE_DIR, 'Makefile.index.template')
  out_path = os.path.join(out_path, 'Makefile')
  rel_path = os.path.relpath(pepperdir, os.path.dirname(out_path))
  template_dict = {
    'projects': targets,
    'rel_sdk' : rel_path,
  }
  RunTemplateFileIfChanged(in_path, out_path, template_dict)
  outdir = os.path.dirname(os.path.abspath(out_path))
  if getos.GetPlatform() == 'win':
    AddMakeBat(pepperdir, outdir)