source: rtems-libbsd/waf_libbsd.py @ b1404f2

55-freebsd-126-freebsd-12
Last change on this file since b1404f2 was 854427b, checked in by Christian Mauderer <christian.mauderer@…>, on 04/06/18 at 08:35:42

waf: Add configurations with different modules.

Update #3351

  • Property mode set to 100644
File size: 18.0 KB
Line 
1#
2#  Copyright (c) 2015-2018 Chris Johns <chrisj@rtems.org>. All rights reserved.
3#
4#  Copyright (c) 2009-2015 embedded brains GmbH.  All rights reserved.
5#
6#   embedded brains GmbH
7#   Dornierstr. 4
8#   82178 Puchheim
9#   Germany
10#   <info@embedded-brains.de>
11#
12#  Copyright (c) 2012 OAR Corporation. All rights reserved.
13#
14#  Redistribution and use in source and binary forms, with or without
15#  modification, are permitted provided that the following conditions
16#  are met:
17#  1. Redistributions of source code must retain the above copyright
18#     notice, this list of conditions and the following disclaimer.
19#  2. Redistributions in binary form must reproduce the above copyright
20#     notice, this list of conditions and the following disclaimer in the
21#     documentation and/or other materials provided with the distribution.
22#
23#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35from __future__ import print_function
36
37import os
38import sys
39import tempfile
40
41import builder
42
43import rtems_waf.rtems as rtems
44
45windows = os.name == 'nt'
46
47if windows:
48    host_shell = 'sh -c '
49else:
50    host_shell = ''
51
52#
53# The waf builder for libbsd.
54#
55class Builder(builder.ModuleManager):
56
57    def __init__(self, trace = False):
58        super(Builder, self).__init__()
59        self.trace = trace
60        self.data = {}
61
62    @staticmethod
63    def _sourceList(bld, files):
64        sources = []
65        if type(files) is dict:
66            for cfg in files:
67                if cfg in ['cflags', 'includes']:
68                    continue
69                if cfg != 'default':
70                    for c in cfg.split(' '):
71                        if not bld.env['HAVE_%s' % (c)]:
72                            continue
73                sources += sorted(files[cfg])
74        else:
75            sources = sorted(files)
76        return sources
77
78    def generate(self, rtems_version):
79
80        def _dataInsert(data, cpu, frag):
81            #
82            # The default handler returns an empty string. Skip it.
83            #
84            if type(frag) is not str:
85                # Start at the top of the tree
86                d = data
87                path = frag[0]
88                if path[0] not in d:
89                    d[path[0]] = {}
90                # Select the sub-part of the tree as the compile options
91                # specialise how files are built.
92                d = d[path[0]]
93                if type(path[1]) is list:
94                    p = ' '.join(path[1])
95                else:
96                    p = path[1]
97                if p not in d:
98                    d[p] = {}
99                d = d[p]
100                if cpu not in d:
101                    d[cpu] = { }
102                config = frag[0][2][0]
103                if config != 'default':
104                    if 'configure' not in data:
105                        data['configure'] = { }
106                    data['configure'][config] = frag[0][2][1]
107                if type(frag[1]) is list:
108                    if config not in d[cpu]:
109                        d[cpu][config] = []
110                    d[cpu][config] += frag[1]
111                else:
112                    d[cpu][config] = frag[1]
113                #
114                # The CPU is for files and the flags and includes are common.
115                #
116                if len(frag) > 3:
117                    if 'cflags' not in d:
118                        d['cflags'] = []
119                    d['cflags'] += frag[2]
120                    d['cflags'] = list(set(d['cflags']))
121                if len(frag) >= 3 and None not in frag[-1]:
122                    if 'includes' not in d:
123                        d['includes'] = []
124                    d['includes'] += frag[-1]
125                    d['includes'] = list(set(d['includes']))
126
127        self.generateBuild()
128
129        self.data = {}
130
131        for mn in self.getEnabledModules():
132            m = self[mn]
133            if m.conditionalOn == "none":
134                for f in m.files:
135                    _dataInsert(self.data, 'all', f.getFragment())
136            for cpu, files in sorted(m.cpuDependentSourceFiles.items()):
137                for f in files:
138                    _dataInsert(self.data, cpu, f.getFragment())
139
140        if self.trace:
141            import pprint
142            pprint.pprint(self.data)
143
144    def bsp_configure(self, conf, arch_bsp):
145        if 'configure' in self.data:
146            for cfg in self.data['configure']:
147                for h in self.data['configure'][cfg]:
148                    conf.check(header_name = h,
149                               features = "c",
150                               includes = conf.env.IFLAGS,
151                               mandatory = False)
152
153    def build(self, bld):
154        #
155        # Localize the config.
156        #
157        config = self.getConfiguration()
158
159        #
160        #
161        # C/C++ flags
162        #
163        common_flags = []
164        common_flags += ['-O%s' % (bld.env.OPTIMIZATION)]
165        if 'common-flags' in config:
166            common_flags += [f for f in config['common-flags']]
167        if bld.env.WARNINGS and 'common-warnings' in config:
168            common_flags += [f for f in config['common-warnings']]
169        elif 'common-no-warnings' in config:
170            common_flags += [f for f in config['common-no-warnings']]
171        if 'cflags' in config:
172            cflags = config['cflags'] + common_flags
173        if 'cxxflags' in config:
174            cxxflags = config['cxxflags'] + common_flags
175
176        #
177        # Defines
178        #
179        defines = []
180        if len(bld.env.FREEBSD_OPTIONS) > 0:
181            for o in bld.env.FREEBSD_OPTIONS.split(','):
182                defines += ['%s=1' % (o.strip().upper())]
183
184        #
185        # Include paths
186        #
187        includes = []
188        if 'cpu-include-paths' in config:
189            cpu = bld.get_env()['RTEMS_ARCH']
190            if cpu == "i386":
191                cpu = 'x86'
192            for i in config['cpu-include-paths']:
193                includes += [i.replace('@CPU@', cpu)]
194        if 'include-paths' in config:
195            includes += config['include-paths']
196        if 'build-include-path' in config:
197            includes += config['build-include-path']
198
199        #
200        # Collect the libbsd uses
201        #
202        libbsd_use = []
203
204        #
205        # Network test configuration
206        #
207        if not os.path.exists(bld.env.NET_CONFIG):
208            bld.fatal('network configuraiton \'%s\' not found' % (bld.env.NET_CONFIG))
209        tags = [ 'NET_CFG_SELF_IP',
210                 'NET_CFG_NETMASK',
211                 'NET_CFG_PEER_IP',
212                 'NET_CFG_GATEWAY_IP' ]
213        try:
214            net_cfg_lines = open(bld.env.NET_CONFIG).readlines()
215        except:
216            bld.fatal('network configuraiton \'%s\' read failed' % (bld.env.NET_CONFIG))
217        lc = 0
218        for l in net_cfg_lines:
219            lc += 1
220            if l.strip().startswith('NET_CFG_'):
221                ls = l.split('=')
222                if len(ls) != 2:
223                    bld.fatal('network configuraiton \'%s\' ' + \
224                              'parse error: %d: %s' % (bld.env.NET_CONFIG, lc, l))
225                lhs = ls[0].strip()
226                rhs = ls[1].strip()
227                sed = 'sed '
228                for t in tags:
229                    if lhs == t:
230                        sed += "-e 's/@%s@/%s/'" % (t, rhs)
231        bld(target = "testsuite/include/rtems/bsd/test/network-config.h",
232            source = "testsuite/include/rtems/bsd/test/network-config.h.in",
233            rule = sed + " < ${SRC} > ${TGT}",
234            update_outputs = True)
235
236        #
237        # Add a copy rule for all headers where the install path and the source
238        # path are not the same.
239        #
240        if 'header-paths' in config:
241            header_build_copy_paths = [
242                hp for hp in config['header-paths'] if hp[2] != '' and not hp[0].endswith(hp[2])
243            ]
244            for headers in header_build_copy_paths:
245                target = os.path.join("build-include", headers[2])
246                start_dir = bld.path.find_dir(headers[0])
247                for header in start_dir.ant_glob(headers[1]):
248                    relsourcepath = header.path_from(start_dir)
249                    targetheader = os.path.join(target, relsourcepath)
250                    bld(features = 'subst',
251                        target = targetheader,
252                        source = header,
253                        is_copy = True)
254
255        #
256        # Add the specific rule based builders
257        #
258
259        #
260        # KVM Symbols
261        #
262        if 'KVMSymbols' in self.data:
263            kvmsymbols = self.data['KVMSymbols']
264            if 'includes' in kvmsymbols['files']:
265                kvmsymbols_includes = kvmsymbols['files']['includes']
266            else:
267                kvmsymbols_includes = []
268            bld(target = kvmsymbols['files']['all']['default'][0],
269                source = 'rtemsbsd/rtems/generate_kvm_symbols',
270                rule = host_shell + './${SRC} > ${TGT}',
271                update_outputs = True)
272            bld.objects(target = 'kvmsymbols',
273                        features = 'c',
274                        cflags = cflags,
275                        includes = kvmsymbols_includes + includes,
276                        source = kvmsymbols['files']['all']['default'][0])
277            libbsd_use += ["kvmsymbols"]
278
279        bld.add_group()
280
281        #
282        # RPC Generation
283        #
284        if 'RPCGen' in self.data:
285            if bld.env.AUTO_REGEN:
286                rpcgen = self.data['RPCGen']
287                rpcname = rpcgen['files']['all']['default'][0][:-2]
288                bld(target = rpcname + '.h',
289                    source = y + '.x',
290                    rule = host_shell + '${RPCGEN} -h -o ${TGT} ${SRC}')
291
292        #
293        # Route keywords
294        #
295        if 'RouteKeywords' in self.data:
296            if bld.env.AUTO_REGEN:
297                routekw = self.data['RouteKeywords']
298                rkwname = routekw['files']['all']['default'][0]
299                rkw_rule = host_shell + 'cat ${SRC} | ' + \
300                           'awk \'BEGIN { r = 0 } { if (NF == 1) ' + \
301                           'printf \\"#define\\\\tK_%%s\\\\t%%d\\\\n\\\\t{\\\\\\"%%s\\\\\\", K_%%s},\\\\n\\", ' + \
302                           'toupper($1), ++r, $1, toupper($1)}\' > ${TGT}'
303                bld(target = rkwname + '.h',
304                    source = rkwname,
305                    rule = rkw_rule)
306
307        #
308        # Lex
309        #
310        if 'lex' in self.data:
311            lexes = self.data['lex']
312            for l in sorted(lexes.keys()):
313                lex = lexes[l]['all']['default']
314                if 'cflags' in lex:
315                    lexDefines = [d[2:] for d in lex['cflags']]
316                else:
317                    lexDefines = []
318                if 'includes' in lex:
319                    lexIncludes = lex['includes']
320                else:
321                    lexIncludes = []
322                lex_rule = host_shell + '${LEX} -P ' + lex['sym'] + ' -t ${SRC} | ' + \
323                           'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' > ${TGT}")'
324                if bld.env.AUTO_REGEN:
325                    bld(target = lex['file'][:-2]+ '.c',
326                        source = lex['file'],
327                        rule = lex_rule)
328                bld.objects(target = 'lex_%s' % (lex['sym']),
329                            features = 'c',
330                            cflags = cflags,
331                            includes = lexIncludes + includes,
332                            defines = defines + lexDefines,
333                            source = lex['file'][:-2] + '.c')
334                libbsd_use += ['lex_%s' % (lex['sym'])]
335
336        #
337        # Yacc
338        #
339        if 'yacc' in self.data:
340            yaccs = self.data['yacc']
341            for y in sorted(yaccs.keys()):
342                yacc = yaccs[y]['all']['default']
343                yaccFile = yacc['file']
344                if yacc['sym'] is not None:
345                    yaccSym = yacc['sym']
346                else:
347                    yaccSym = os.path.basename(yaccFile)[:-2]
348                yaccHeader = '%s/%s' % (os.path.dirname(yaccFile), yacc['header'])
349                if 'cflags' in yacc:
350                    yaccDefines = [d[2:] for d in yacc['cflags']]
351                else:
352                    yaccDefines = []
353                if 'includes' in yacc:
354                    yaccIncludes = yacc['includes']
355                else:
356                    yaccIncludes = []
357                yacc_rule = host_shell + '${YACC} -b ' + yaccSym + \
358                            ' -d -p ' + yaccSym + ' ${SRC} && ' + \
359                            'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' < ' + yaccSym + '.tab.c > ${TGT} && ' + \
360                            'rm -f ' + yaccSym + '.tab.c && mv ' + yaccSym + '.tab.h ' + yaccHeader
361                if bld.env.AUTO_REGEN:
362                    bld(target = yaccFile[:-2] + '.c',
363                        source = yaccFile,
364                        rule = yacc_rule)
365                bld.objects(target = 'yacc_%s' % (yaccSym),
366                            features = 'c',
367                            cflags = cflags,
368                            includes = yaccIncludes + includes,
369                            defines = defines + yaccDefines,
370                            source = yaccFile[:-2] + '.c')
371                libbsd_use += ['yacc_%s' % (yaccSym)]
372
373        #
374        # We have 'm' different sets of flags and there can be 'n' cpus
375        # specific files for those flags.
376        #
377        objs = 0
378        sources = sorted(self.data['sources'])
379        if 'default' in sources:
380            sources.remove('default')
381        for flags in sources:
382            objs += 1
383            build = self.data['sources'][flags]
384            target = 'objs%02d' % (objs)
385            bld_sources = Builder._sourceList(bld, build['all'])
386            archs = sorted(build)
387            for i in ['all', 'cflags', 'includes']:
388                if i in archs:
389                    archs.remove(i)
390            for arch in archs:
391                if bld.get_env()['RTEMS_ARCH'] == arch:
392                    bld_sources += Builder._sourceList(bld, build[arch])
393            if 'cflags' in build:
394                bld_defines = [d[2:] for d in build['cflags']]
395            else:
396                bld_defines = []
397            if 'includes' in build:
398                bld_includes = build['includes']
399            else:
400                bld_includes = []
401            bld.objects(target = target,
402                        features = 'c',
403                        cflags = cflags,
404                        includes = sorted(bld_includes) + includes,
405                        defines = defines + sorted(bld_defines),
406                        source = bld_sources)
407            libbsd_use += [target]
408
409        #
410        # We hold the 'default' cflags set of files to the end to create the
411        # static library with.
412        #
413        build = self.data['sources']['default']
414        bld_sources = Builder._sourceList(bld, build['all'])
415        archs = sorted(build)
416        archs.remove('all')
417        for arch in archs:
418            if bld.get_env()['RTEMS_ARCH'] == arch:
419                bld_sources += Builder._sourceList(bld, build[arch])
420        bld.stlib(target = 'bsd',
421                  features = 'c cxx',
422                  cflags = cflags,
423                  cxxflags = cxxflags,
424                  includes = includes,
425                  defines = defines,
426                  source = bld_sources,
427                  use = libbsd_use)
428
429        #
430        # Installs.
431        #
432        # Header file collector.
433        #
434        arch_lib_path = rtems.arch_bsp_lib_path(bld.env.RTEMS_VERSION,
435                                                bld.env.RTEMS_ARCH_BSP)
436        arch_inc_path = rtems.arch_bsp_include_path(bld.env.RTEMS_VERSION,
437                                                    bld.env.RTEMS_ARCH_BSP)
438
439        bld.install_files("${PREFIX}/" + arch_lib_path, ["libbsd.a"])
440
441        if 'header-paths' in config:
442            headerPaths = config['header-paths']
443            cpu = bld.get_env()['RTEMS_ARCH']
444            if cpu == "i386":
445                cpu = 'x86'
446            for headers in headerPaths:
447                # Get the dest path
448                ipath = os.path.join(arch_inc_path, headers[2])
449                start_dir = bld.path.find_dir(headers[0].replace('@CPU@', cpu))
450                if start_dir != None:
451                    bld.install_files("${PREFIX}/" + ipath,
452                                      start_dir.ant_glob(headers[1]),
453                                      cwd = start_dir,
454                                      relative_trick = True)
455
456        #
457        # Tests
458        #
459        tests = self.data['tests']
460        for testName in sorted(tests):
461            test = self.data['tests'][testName]['all']
462            test_source = []
463            for cfg in test:
464                build_test = True
465                if cfg != 'default':
466                    for c in cfg.split(' '):
467                        if not bld.env['HAVE_%s' % (c)]:
468                            build_test = False
469                            break
470                if build_test:
471                    test_sources = ['testsuite/%s/%s.c' % (testName, f) \
472                                    for f in test[cfg]['files']]
473            if build_test:
474                bld.program(target = '%s.exe' % (testName),
475                            features = 'cprogram',
476                            cflags = cflags,
477                            includes = includes,
478                            source = test_sources,
479                            use = ['bsd'],
480                            lib = ['m', 'z'],
481                            install_path = None)
Note: See TracBrowser for help on using the repository browser.