source: rtems-libbsd/waf_libbsd.py @ a6a6d54

55-freebsd-126-freebsd-12
Last change on this file since a6a6d54 was a6a6d54, checked in by Christian Mauderer <christian.mauderer@…>, on 03/27/18 at 07:31:49

waf: Fix freebsd-to-rtems.py.

Update #3351

  • Property mode set to 100644
File size: 18.1 KB
RevLine 
[f7a09b5]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
[d797c5d]127        self.generateBuild()
128
[f7a09b5]129        self.data = {}
130
[d797c5d]131        for mn in self.getEnabledModules():
[f7a09b5]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 init(self, ctx):
145        pass
146
147    def options(self, opt):
148        pass
149
150    def bsp_configure(self, conf, arch_bsp):
151        if 'configure' in self.data:
152            for cfg in self.data['configure']:
153                for h in self.data['configure'][cfg]:
154                    conf.check(header_name = h,
155                               features = "c",
156                               includes = conf.env.IFLAGS,
157                               mandatory = False)
158
159    def configure(self, conf):
160        pass
161
162    def build(self, bld):
163        #
164        # Localize the config.
165        #
166        config = self.getConfiguration()
167
168        #
169        #
170        # C/C++ flags
171        #
172        common_flags = []
173        common_flags += ['-O%s' % (bld.env.OPTIMIZATION)]
174        if 'common-flags' in config:
175            common_flags += [f for f in config['common-flags']]
176        if bld.env.WARNINGS and 'common-warnings' in config:
177            common_flags += [f for f in config['common-warnings']]
178        elif 'common-no-warnings' in config:
179            common_flags += [f for f in config['common-no-warnings']]
180        if 'cflags' in config:
181            cflags = config['cflags'] + common_flags
182        if 'cxxflags' in config:
183            cxxflags = config['cxxflags'] + common_flags
184
185        #
186        # Defines
187        #
188        defines = []
189        if len(bld.env.FREEBSD_OPTIONS) > 0:
190            for o in bld.env.FREEBSD_OPTIONS.split(','):
191                defines += ['%s=1' % (o.strip().upper())]
192
193        #
194        # Include paths
195        #
196        includes = []
197        if 'cpu-include-paths' in config:
198            cpu = bld.get_env()['RTEMS_ARCH']
199            if cpu == "i386":
200                cpu = 'x86'
201            for i in config['cpu-include-paths']:
202                includes += [i.replace('@CPU@', cpu)]
203        if 'include-paths' in config:
204            includes += config['include-paths']
205        if 'build-include-path' in config:
206            includes += config['build-include-path']
207
208        #
209        # Collect the libbsd uses
210        #
211        libbsd_use = []
212
213        #
214        # Network test configuration
215        #
216        if not os.path.exists(bld.env.NET_CONFIG):
217            bld.fatal('network configuraiton \'%s\' not found' % (bld.env.NET_CONFIG))
218        tags = [ 'NET_CFG_SELF_IP',
219                 'NET_CFG_NETMASK',
220                 'NET_CFG_PEER_IP',
221                 'NET_CFG_GATEWAY_IP' ]
222        try:
223            net_cfg_lines = open(bld.env.NET_CONFIG).readlines()
224        except:
225            bld.fatal('network configuraiton \'%s\' read failed' % (bld.env.NET_CONFIG))
226        lc = 0
227        for l in net_cfg_lines:
228            lc += 1
229            if l.strip().startswith('NET_CFG_'):
230                ls = l.split('=')
231                if len(ls) != 2:
232                    bld.fatal('network configuraiton \'%s\' ' + \
233                              'parse error: %d: %s' % (bld.env.NET_CONFIG, lc, l))
234                lhs = ls[0].strip()
235                rhs = ls[1].strip()
236                sed = 'sed '
237                for t in tags:
238                    if lhs == t:
239                        sed += "-e 's/@%s@/%s/'" % (t, rhs)
240        bld(target = "testsuite/include/rtems/bsd/test/network-config.h",
241            source = "testsuite/include/rtems/bsd/test/network-config.h.in",
242            rule = sed + " < ${SRC} > ${TGT}",
243            update_outputs = True)
244
245        #
246        # Add a copy rule for all headers where the install path and the source
247        # path are not the same.
248        #
249        if 'header-paths' in config:
250            header_build_copy_paths = [
251                hp for hp in config['header-paths'] if hp[2] != '' and not hp[0].endswith(hp[2])
252            ]
253            for headers in header_build_copy_paths:
254                target = os.path.join("build-include", headers[2])
255                start_dir = bld.path.find_dir(headers[0])
256                for header in start_dir.ant_glob(headers[1]):
257                    relsourcepath = header.path_from(start_dir)
258                    targetheader = os.path.join(target, relsourcepath)
259                    bld(features = 'subst',
260                        target = targetheader,
261                        source = header,
262                        is_copy = True)
263
264        #
265        # Add the specific rule based builders
266        #
267
268        #
269        # KVM Symbols
270        #
271        if 'KVMSymbols' in self.data:
272            kvmsymbols = self.data['KVMSymbols']
273            if 'includes' in kvmsymbols['files']:
274                kvmsymbols_includes = kvmsymbols['files']['includes']
275            else:
276                kvmsymbols_includes = []
277            bld(target = kvmsymbols['files']['all']['default'][0],
278                source = 'rtemsbsd/rtems/generate_kvm_symbols',
279                rule = host_shell + './${SRC} > ${TGT}',
280                update_outputs = True)
281            bld.objects(target = 'kvmsymbols',
282                        features = 'c',
283                        cflags = cflags,
284                        includes = kvmsymbols_includes + includes,
285                        source = kvmsymbols['files']['all']['default'][0])
286            libbsd_use += ["kvmsymbols"]
287
288        bld.add_group()
289
290        #
291        # RPC Generation
292        #
293        if 'RPCGen' in self.data:
294            if bld.env.AUTO_REGEN:
295                rpcgen = self.data['RPCGen']
296                rpcname = rpcgen['files']['all']['default'][0][:-2]
297                bld(target = rpcname + '.h',
298                    source = y + '.x',
299                    rule = host_shell + '${RPCGEN} -h -o ${TGT} ${SRC}')
300
301        #
302        # Route keywords
303        #
304        if 'RouteKeywords' in self.data:
305            if bld.env.AUTO_REGEN:
306                routekw = self.data['RouteKeywords']
307                rkwname = routekw['files']['all']['default'][0]
308                rkw_rule = host_shell + 'cat ${SRC} | ' + \
309                           'awk \'BEGIN { r = 0 } { if (NF == 1) ' + \
310                           'printf \\"#define\\\\tK_%%s\\\\t%%d\\\\n\\\\t{\\\\\\"%%s\\\\\\", K_%%s},\\\\n\\", ' + \
311                           'toupper($1), ++r, $1, toupper($1)}\' > ${TGT}'
312                bld(target = rkwname + '.h',
313                    source = rkwname,
314                    rule = rkw_rule)
315
316        #
317        # Lex
318        #
319        if 'lex' in self.data:
320            lexes = self.data['lex']
321            for l in sorted(lexes.keys()):
322                lex = lexes[l]['all']['default']
323                if 'cflags' in lex:
324                    lexDefines = [d[2:] for d in lex['cflags']]
325                else:
326                    lexDefines = []
327                if 'includes' in lex:
328                    lexIncludes = lex['includes']
329                else:
330                    lexIncludes = []
331                lex_rule = host_shell + '${LEX} -P ' + lex['sym'] + ' -t ${SRC} | ' + \
332                           'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' > ${TGT}")'
333                if bld.env.AUTO_REGEN:
334                    bld(target = lex['file'][:-2]+ '.c',
335                        source = lex['file'],
336                        rule = lex_rule)
337                bld.objects(target = 'lex_%s' % (lex['sym']),
338                            features = 'c',
339                            cflags = cflags,
340                            includes = lexIncludes + includes,
341                            defines = defines + lexDefines,
342                            source = lex['file'][:-2] + '.c')
343                libbsd_use += ['lex_%s' % (lex['sym'])]
344
345        #
346        # Yacc
347        #
348        if 'yacc' in self.data:
349            yaccs = self.data['yacc']
350            for y in sorted(yaccs.keys()):
351                yacc = yaccs[y]['all']['default']
352                yaccFile = yacc['file']
353                if yacc['sym'] is not None:
354                    yaccSym = yacc['sym']
355                else:
356                    yaccSym = os.path.basename(yaccFile)[:-2]
357                yaccHeader = '%s/%s' % (os.path.dirname(yaccFile), yacc['header'])
358                if 'cflags' in yacc:
359                    yaccDefines = [d[2:] for d in yacc['cflags']]
360                else:
361                    yaccDefines = []
362                if 'includes' in yacc:
363                    yaccIncludes = yacc['includes']
364                else:
365                    yaccIncludes = []
366                yacc_rule = host_shell + '${YACC} -b ' + yaccSym + \
367                            ' -d -p ' + yaccSym + ' ${SRC} && ' + \
368                            'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' < ' + yaccSym + '.tab.c > ${TGT} && ' + \
369                            'rm -f ' + yaccSym + '.tab.c && mv ' + yaccSym + '.tab.h ' + yaccHeader
370                if bld.env.AUTO_REGEN:
371                    bld(target = yaccFile[:-2] + '.c',
372                        source = yaccFile,
373                        rule = yacc_rule)
374                bld.objects(target = 'yacc_%s' % (yaccSym),
375                            features = 'c',
376                            cflags = cflags,
377                            includes = yaccIncludes + includes,
378                            defines = defines + yaccDefines,
379                            source = yaccFile[:-2] + '.c')
380                libbsd_use += ['yacc_%s' % (yaccSym)]
381
382        #
383        # We have 'm' different sets of flags and there can be 'n' cpus
384        # specific files for those flags.
385        #
386        objs = 0
387        sources = sorted(self.data['sources'])
388        if 'default' in sources:
389            sources.remove('default')
390        for flags in sources:
391            objs += 1
392            build = self.data['sources'][flags]
393            target = 'objs%02d' % (objs)
394            bld_sources = Builder._sourceList(bld, build['all'])
395            archs = sorted(build)
396            for i in ['all', 'cflags', 'includes']:
397                if i in archs:
398                    archs.remove(i)
399            for arch in archs:
400                if bld.get_env()['RTEMS_ARCH'] == arch:
401                    bld_sources += Builder._sourceList(bld, build[arch])
402            if 'cflags' in build:
403                bld_defines = [d[2:] for d in build['cflags']]
404            else:
405                bld_defines = []
406            if 'includes' in build:
407                bld_includes = build['includes']
408            else:
409                bld_includes = []
410            bld.objects(target = target,
411                        features = 'c',
412                        cflags = cflags,
413                        includes = sorted(bld_includes) + includes,
414                        defines = defines + sorted(bld_defines),
415                        source = bld_sources)
416            libbsd_use += [target]
417
418        #
419        # We hold the 'default' cflags set of files to the end to create the
420        # static library with.
421        #
422        build = self.data['sources']['default']
423        bld_sources = Builder._sourceList(bld, build['all'])
424        archs = sorted(build)
425        archs.remove('all')
426        for arch in archs:
427            if bld.get_env()['RTEMS_ARCH'] == arch:
428                bld_sources += Builder._sourceList(bld, build[arch])
429        bld.stlib(target = 'bsd',
430                  features = 'c cxx',
431                  cflags = cflags,
432                  cxxflags = cxxflags,
433                  includes = includes,
434                  defines = defines,
435                  source = bld_sources,
436                  use = libbsd_use)
437
438        #
439        # Installs.
440        #
441        # Header file collector.
442        #
443        arch_lib_path = rtems.arch_bsp_lib_path(bld.env.RTEMS_VERSION,
444                                                bld.env.RTEMS_ARCH_BSP)
445        arch_inc_path = rtems.arch_bsp_include_path(bld.env.RTEMS_VERSION,
446                                                    bld.env.RTEMS_ARCH_BSP)
447
448        bld.install_files("${PREFIX}/" + arch_lib_path, ["libbsd.a"])
449
450        if 'header-paths' in config:
451            headerPaths = config['header-paths']
452            cpu = bld.get_env()['RTEMS_ARCH']
453            if cpu == "i386":
454                cpu = 'x86'
455            for headers in headerPaths:
456                # Get the dest path
457                ipath = os.path.join(arch_inc_path, headers[2])
458                start_dir = bld.path.find_dir(headers[0].replace('@CPU@', cpu))
459                if start_dir != None:
460                    bld.install_files("${PREFIX}/" + ipath,
461                                      start_dir.ant_glob(headers[1]),
462                                      cwd = start_dir,
463                                      relative_trick = True)
464
465        #
466        # Tests
467        #
468        tests = self.data['tests']
469        for testName in sorted(tests):
470            test = self.data['tests'][testName]['all']
471            test_source = []
472            for cfg in test:
473                build_test = True
474                if cfg != 'default':
475                    for c in cfg.split(' '):
476                        if not bld.env['HAVE_%s' % (c)]:
477                            build_test = False
478                            break
479                if build_test:
480                    test_sources = ['testsuite/%s/%s.c' % (testName, f) \
481                                    for f in test[cfg]['files']]
482            if build_test:
483                bld.program(target = '%s.exe' % (testName),
484                            features = 'cprogram',
485                            cflags = cflags,
486                            includes = includes,
487                            source = test_sources,
488                            use = ['bsd'],
489                            lib = ['m', 'z'],
490                            install_path = None)
Note: See TracBrowser for help on using the repository browser.